JastinBall
JastinBall

Reputation: 893

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.

Upvotes: 6

Views: 834

Answers (4)

Madhu
Madhu

Reputation: 2384

I've seen this a couple of times regarding NSStrings, the retainCount returns the maximum count instead of the actual one when you try to look at retainCounts of strings in this manner.

Try this;

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

Edit: Restored NSUInteger

Upvotes: 1

deanWombourne
deanWombourne

Reputation: 38475

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.

Upvotes: 4

omz
omz

Reputation: 53561

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.

Upvotes: 15

Silvae
Silvae

Reputation: 604

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?

Upvotes: 12

Related Questions