Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 422
JastinBall Avatar asked Sep 08 '11 15:09

JastinBall


3 Answers

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.

like image 59
omz Avatar answered Nov 10 '22 10:11

omz


This doesn't directly answer your question, but retainCount is not really all that useful and should not be used for testing. See this SO post for details. When to use -retainCount?

like image 12
Silvae Avatar answered Nov 10 '22 11:11

Silvae


While NSString's are an odd case (there are others in the framework) you might also run across this in other clases - it's one of the ways of creating a singleton object.

A singleton only exists once in the app and it's pretty important that it never gets released! Therefore, it will overwrite some methods of NSObject including (but not limited to):

- (id)release {
    // Ignore the release!
    return self;
}

- (NSUInteger)retainCount {
    // We are never going to be released
    return UINT_MAX;
}

This object can never be released and tells the framework that it's a singleton by having a ludicrously high retain count.

Checkout this link for more information about singleton objects.

like image 4
deanWombourne Avatar answered Nov 10 '22 10:11

deanWombourne