RetainCount of NSString and NSMutableString in IOS development (41)

Source: Internet
Author: User

1. string constants

NSString * s = @ "test ";

NSLog (@ "s: % lx", [s retainCount]); // ffffffffffffff (UINT_MAX (Maximum value an 'unsigned int '))

Because "test" is a String constant, the system does not reclaim it and does not reference it for counting, even if we retain or release s.

 

2. stringWithFormat

NSString * s = [NSString stringWithFormat: @ "% s", "test"];

NSLog (@ "s: % d", [s retainCount]); // 1

The NSString created using stringWithFormat is a variable, and the reference count is performed.

 

2. stringWithString

The stringWithString method is special: Its retainCount depends on the string object followed by it.

NSString * s1 = [NSString stringWithString: @ "test"];

NSString * s2 = [NSString stringWithString: [NSString stringWithFormat: @ "test, % d", 1];

NSLog (@ "s1: % d", [s1 retainCount]); // 2147483647

NSLog (@ "s2: % d", [s2 retainCount]); // 2

We can see that the first object is a constant, and the implementation of its retainCount method returns maxIntValue.

The second is 2, which is well understood here. It also proves that this method generates a reference to another object. An object instance with two stringwithstrings whose retainCount is 2 is also managed by the current AutoreleasePool.

 

 

NSMutableString * myStr3 = [NSMutableString stringWithString: @ "string 3"];

Output 1 with reference count

 

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.