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.