views:

109

answers:

3

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.

A: 

See this... http://stackoverflow.com/questions/1407517/can-you-send-retain-counts-to-nslog-to-aid-learning

Lee Armstrong
How does that help? All it says is “yes”, and that's even the wrong answer. (`retainCount` is *not* useful for learning because it is so often misleading.)
Peter Hosey
+2  A: 

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.

Peter Hosey
+7  A: 

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.)

Ahruman
Yes I had the Garbage Collector enabled. I was playing around with the setting the day before and totally forgot about it. Many thanks!
Holli