views:

60

answers:

4

Using objective-c on the iPhone, what is wrong with this code? Is it leaking memory? Why? How would I do this correctly?

NSMutableString *result = [NSMutableString stringWithFormat:@"the value is %d", i];

... then later in my code... I might need to change this to:

result = [NSMutableString stringWithFormat:@"the value is now %d", i];

I need to use stringWithFormat a 2nd time... but isn't that creating a NEW string and not correctly freeing the old one?

+5  A: 

No, it doesn't leak memory because stringWithFormat: returns an autoreleased object.

Ole Begemann
A: 

You could use the instance method "setString" for your already existing NSMutableString, like this:

[ result setString:[NSString stringWithFormat:@"the value is now %d", i] ];
Olli
Assuming you mean `[NSString stringWithFormat`, which misses the point entirely: it creates a new string and then copies its contents to the mutable string, instead of simply reusing the memory of the mutable string.
tc.
A: 

If you really want to reuse the string, you can use something like

[result setString:@""];
[result appendFormat:@"the value is now %d", i];

However, unless you notice a performance/memory problem, just use

NSString *result = [NSString stringWithFormat:@"the value is %d", i];

/* ... */

result = [NSString stringWithFormat:@"the value is now %d", i];

It's generally easier to work with immutable objects because they can't change under your feet.

tc.
A: 

What you have seems to me to be the natural way to replace a mutable string with new content, unless you have other references to the same mutable string elsewhere.

If you don't have other references to it and you are reusing the string only to improve performance/memory footprint, that sounds like premature optimisation.

By the way, you do not own a string you obtain via stringWithFormat: so you do not need to (Indeed must not) release it.

JeremyP