A section on reading a book todayCodeWhen nsstring is instantiated, sometimes the initwithformat method is used, and sometimes the stringwithformat method is used. What 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: When label. Text =... is used, it is actually the settext method of the label that is implicitly called. This will retain the string variable Text inside the label (even if this stringContentFollowed by the passed string contentSameBut the system is still regarded as twoDifferentSo in the final release label, only the text string inside the label is actually released, but the string originally generated with initwithformat is not released, resulting in leakage.
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.