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