When I read a piece of code today, I found that when NSString is instantiated, sometimes the initWithFormat method is used, and sometimes the stringWithFormat method is used. How should I choose?
Differences:
1. initWithFormat is the instance method.
It can only be called through NSString * str = [[NSString alloc] initWithFormat: @ "% @", @ "Hello World"], but must be manually release to release memory resources
2. stringWithFormat is a class method.
You can directly use NSString * str = [NSString stringWithFormat: @ "% @", @ "Hello World"] for calling. The memory management is autorelease, and explicit release is not required.
In addition, there is a foreign post dedicated to this discussion (http://www.iphonedevsdk.com/forum/iphone-sdk-development/29249-nsstring-initwithformat-vs-stringwithformat.html)
A common error is also raised:
Label. text = [[NSString alloc] initWithFormat: @ "% @", @ "abc"];
Finally, release the label to the release in dealloc.
However, memory leakage still occurs!
The reason is: Use label. text =... it is actually the setText method of the label that is implicitly called. This retakes the text variable inside the label (even if the content of this string is the same as that of the passed string, but the system is still treated as two different string objects), so in the final release label, only the text string inside the label is actually released, but the string originally generated using initWithFormat is not released, eventually caused a leak.
There are two solutions:
1,
NSString * str = [[NSString alloc] initWithFormat: @ "% @", @ "abc"];
Label. text = str;
[Str release]
And then [label release] In dealloc.
2,
Label. text = [NSString stringWithFormat: @ "% @", @ "abc"];
Then the rest will be handed over to the nasimoreleasepool.
Finally, if you are not sure whether your code has a memory leak, you can use Build --> Build And Analyze in Xcode to perform a preliminary check.
Author: Yang Guo under the bodhi tree
Source: http://www.cnblogs.com/yjmyzz/archive/2011/02/25/1965338.html
The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.