discuss-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSMutableString -initWithFormat appends to existing text


From: David Chisnall
Subject: Re: NSMutableString -initWithFormat appends to existing text
Date: Wed, 18 Apr 2018 08:53:24 +0100

On 18 Apr 2018, at 08:42, Mick Bert <micbert75@gmail.com> wrote:
> 
> Hello.
> Can I make question about how to use API, in this list?
> I decided to use GNUstep for all the working activity where I have the
> chance, just to practice my obj-c/gnustep experience.
> 
> Well, in a method I am using and re-using an object of
> NSMutableString, so I create it once with +stringWithCapacity, an than
> I initialize with -initWithFormat. Something like:
> 
>  NSMutableString *outmsg=[NSMutableString stringWithCapacity: 1000];
>  outmsg=[outmsg initWithFormat: @"first: %@", [arr objectAtIndex: 0]];
>  // use outmsg
>  outmsg=[outmsg initWithFormat: @"second: %@", [arr objectAtIndex: 1]];
>  // use outmsg
> outmsg=[outmsg initWithFormat: @"third: %@", [arr objectAtIndex: 2]];
>  // use outmsg
> 
> What I observe is that every time I invoke -initWithFormat the text is
> appended at the end of the existing string. Is it the right behavior
> to expect? Am I doing something wrong?

That’s not what I would expect to happen, but in general Objective-C considers 
calling an init-family method on the same object to be undefined behaviour 
unless the class explicitly advertises support for this.  Most init-family 
methods assume that all ivars are zero on entry and so will either leak memory 
or do very odd things if you call them on an already-initialised object.

It’s somewhat unfortunate that Objective-C has +alloc and -dealloc, but doesn’t 
have a -deinit method to correspond to -init and reset an object into a state 
where it is safe to reinitialise it, though with the performance of modern 
memory allocators you don’t actually save very much by skipping reallocation in 
most cases.  The few cases where it does make sense are usually done by a 
-reset or similar method that efficiently restores an object to a pristine 
state.

Note that, in your example, the +stringWithCapacity: method is expected to call 
an init-family method and so any call to any other initialiser is likely to be 
undefined.

David




reply via email to

[Prev in Thread] Current Thread [Next in Thread]