开发者

Reusing NSMutableString correctly on the iPhone

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?


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


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

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜