stringWithFormat vs. initWithFormat on NSString

你说的曾经没有我的故事 提交于 2019-12-02 19:14:53

stringWithFormat: returns an autoreleased string; initWithFormat: returns a string that must be released by the caller. The former is a so-called "convenience" method that is useful for short-lived strings, so the caller doesn't have to remember to call release.

I actually came across this blog entry on memory optimizations just yesterday. In it, the author gives specific reasons why he chooses to use [[NSString alloc] initWithFormat:@"..."] instead of [NSString stringWithFormat:@"..."]. Specifically, iOS devices may not auto-release the memory pool as soon as you would prefer if you create an autorelease object.

The former version requires that you manually release it, in a construct such as this:

NSString *remainingStr = nil;
if (remaining > 1)
    remainingStr = [[NSString alloc] initWithFormat:@"You have %d left to go!", remaining];
else if (remaining == 1)
    remainingStr = [[NSString alloc] initWithString:@"You have 1 left to go!"];
else
    remainingStr = [[NSString alloc] initWithString:@"You have them all!"];

NSString *msg = [NSString stringWithFormat:@"Level complete! %@", remainingStr];

[remainingStr release];

[self displayMessage:msg];

Here, remainingStr was only needed temporarily, and so to avoid the autorelease (which may happen MUCH later in the program), I explicitly handle the memory as I need it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!