NSString for iOS Study Notes

Source: Internet
Author: User

Various NSString initialization and retainCount

int main(int argc, const char * argv[]){    @autoreleasepool {                NSString *s1 = @"Constant string";        NSLog(@"%lx", [s1 retainCount]); // ffffffffffffffff                NSString *s2 = [NSString stringWithString:@"string 2"];        NSLog(@"%lx", [s2 retainCount]); // ffffffffffffffff                NSString *s3 = [NSString stringWithFormat:@"%s", @"string 3"];        NSLog(@"%lx", [s3 retainCount]); // 1                NSMutableString *s4 = [NSMutableString stringWithString:@"string 4"];        NSLog(@"%lx", [s4 retainCount]); // 1                NSString *s5 = [NSString stringWithString:[NSString stringWithFormat:@"string 5"]];        NSLog(@"%lx", [s5 retainCount]); // 2                NSString *s6 = [[NSString alloc] init];        NSLog(@"%lx", [s6 retainCount]); // ffffffffffffffff        s6 = @"string 6";        NSLog(@"%lx", [s6 retainCount]); // ffffffffffffffff    }    return 0;}

 

The space allocation of constant strings in memory is different from that of other objects. They do not reference the counting mechanism, because these objects cannot be released forever. This is why the retainCount message is sent to s1, And it returns

Ffffffffffffff, in fact, in the standard header file <limits. h>, this value is defined as the largest unsigned integer, or UINT_MAX.

This also appliesUse a constant string to initialize an immutable object: This type of object does not have a value.

In the following sentence:

NSMutableString *s4 = [NSMutableString stringWithString:@"string 4"];

The variable s4 is set as a copy of the constant string @ "string 4. The reason for making a string copy is that the stringWithString: message is sent to NSMutableString, indicating that the content of the string may change during program execution. The content of a constant string cannot be changed. Therefore, the system cannot set the variable s4 to point to the constant string @ "string 4", while s2 can.

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.