Search code examples
objective-cretain

copy an NSMutableString instance returns retainCount of -1


Can someone explain why the last line prints out -1? It happens when copy is called on a NSMutableString, I expect the returnCount of strFour to be 1, since an immutable copy should be returned.

    NSMutableString *str =[NSMutableString stringWithString:@"hi"];
NSLog(@"new instantiated variable has a retain cout:");
NSLog(@"%d",[str retainCount]);  //1, str is a pointer, its value is a memory address

NSMutableString *strFour =[str copy]; //receiver str is mutable, copy returns an immutable 
NSLog(@"%d",[strFour retainCount]); ////strFour s retain count should be 1, but it had a retain count of -1

Thanks a lot.


Solution

  • Never bother looking at the retain count of an object. It is always meaningless to do so. The retain count is likely affected by optimisations “under the hood”. These optimisations rely on the fact that your code follows the Cocoa Memory Management Guidelines. Just worry about sticking to those guidelines and don't bother looking directly at the retain count.

    One reason why it could be (-1) because the string “hi” may be cached somewhere and your copy is referring to the cached string. Keep in mind that the retain count is actually an unsigned integer. The documentation dor -retainCount says that for objects that never get released, the retain count should be UINT_MAX (which when printed as a signed decimal will come out as “-1”).