TalkingCode
TalkingCode

Reputation: 13557

Objective-C : Why is my retain count not 1?

I have this very simple program where I just create an object and look at the retain count.

#import <Foundation/Foundation.h>
#import "GeometryCalculator.h"

int main (int argc, const char * argv[]) {
     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

     GeometryCalculator *calculator = [[GeometryCalculator alloc] init];
     NSLog(@"Counter: %d", [calculator retainCount]);

    [calculator release];

        [pool drain];
        return 0;  
}

I expected my retainCount to be 1 but it is 16863520. The Class GeometryCalculator is totally empty. No methodes, no instance variables.

Upvotes: 0

Views: 333

Answers (2)

Jens Ayton
Jens Ayton

Reputation: 14558

You are testing this with garbage collection enabled. The result of retainCount is undefined under garbage collection, but in practical terms, it returns the pointer value of your object because that’s the fastest undefined thing to do (in this case, 0x1015120).

(Trivia: you’re also testing in a 32-bit process. If it was a 64-bit process, you’d get the high word of the pointer because of the type truncation Peter refers to, and that would be a lower value.)

Upvotes: 7

Peter Hosey
Peter Hosey

Reputation: 96323

The correct type specifier is %lu, not %d. The retainCount method returns NSUInteger, which is unsigned and equal in size to a long—so, practically, it's equivalent to unsigned long, for which you use %lu. %d is int, which is signed and (on some architectures) shorter. Using wrong type specifiers is a good way to get wrong output. So, see whether fixing that corrects your output.

If it doesn't, then this is certainly a puzzle.

Upvotes: 3

Related Questions