Search code examples
iphoneobjective-ciosxcode4

retainCount shows MaxInt


After trying to print retainCount of object I get 2147483647. Why do I get such a result? It should be 1, shouldn't?

NSString *myStr = [NSString new];
NSUInteger retCount = [myStr retainCount];
NSLog(@"refCount = %u", retCount);

2011-09-08 17:59:18.759 Test[51972:207] refCount = 2147483647

I use XCode Version 4.1. Tried compilers GCC 4.2 and LLVM GCC 4.2 - the same result. Garbage Collection option was set to unsupported.


Solution

  • NSString is somewhat special when it comes to memory management. String literals (something like @"foo") are effectively singletons, every string with the same content is the same object because it can't be modified anyway. As [NSString new] always creates an empty string that cannot be modified, you'll always get the same instance which cannot be released (thus the high retainCount).

    Try this snippet:

    NSString *string1 = [NSString new];
    NSString *string2 = [NSString new];
    NSLog(@"Memory address of string1: %p", string1);
    NSLog(@"Memory address of string2: %p", string2);
    

    You'll see that both strings have the same memory address and are therefore the same object.