Objective-C: Should nsstring use initwithformat? Or stringwithformat?

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.