NSString retain Count
Solution 1:
The compiler is smarter than you.
It sees @"Hello world"
and thinks "Aha! A constant string!"
It then sees [[NSString alloc] initWithString:@"Hello world!"]
and thinks "Aha! An immutable object created with a constant string!"
It then collapses both of them down into a single NSConstantString
, which has a retainCount
of UINT_MAX
, so that it can never be released.
Solution 2:
NSString *str = [[NSString alloc] initXXX
usually would allocate some RAM and return you a pointer. This RAM would then be subject to releases and reatins. However, when you do:
NSString *str = [[NSString alloc] initWithString:@"Hello World"];
the string returned is @"Hello World", which is already allocated because it was a string literal. Since it is a string literal, there is no way to release it, and thus the system has to mark it as unreleasable. The way it does that is to set its retain count to the max integer value.
NString *str = [[NSString alloc] initWithFormat:@"Hello World. Today is @%", todayDate];
This string will have a retainCount of 1. Although there is a string constant in there, it is appended to by another string. Since you can't modify that constant string, a copy of the "Hello World. " string is made, and the content of the todayDate string is added to that. That memory now is given ownership to the caller, with a retainCount of 1.
Solution 3:
The string is being optimized at compile-time to a statically allocated instance of NSString in order to save on some variable overhead and the like. You're seeing such a high retain count because static strings have a retain count of the maximum integer on whatever platform you're developing on.