Question

Have a look at this code-snippet with a simple retain/release scenario:

#import <Foundation/Foundation.h>

@interface SomeClass : NSObject
@end

@implementation SomeClass
@end

int main(int argc, const char * argv[])
{
    SomeClass *aClass = [[SomeClass alloc] init];
    NSLog(@"retainCount: %lu", [aClass retainCount]);

    [aClass retain];
    NSLog(@"retainCount: %lu", [aClass retainCount]);

    [aClass release];
    NSLog(@"retainCount: %lu", [aClass retainCount]);

    [aClass release];
    NSLog(@"retainCount: %lu", [aClass retainCount]);

    return 0;
}

That's the resulting output:

2013-04-29 17:33:50.695 retainCount: 1
2013-04-29 17:33:50.697 retainCount: 2
2013-04-29 17:33:50.697 retainCount: 1
2013-04-29 17:33:50.698 retainCount: 1

The last retainCount should either be "0" or the app should crash. Why is the result "1" ?!

Was it helpful?

Solution

http://www.whentouseretaincount.com

Messaging a deallocated object is undefined behavior. It might crash, it might work, it might do something completely unexpected.

Upon deallocation, your program won't waste any cycles mucking with the freshly deallocated memory (unless you turn on malloc scribble), thus the undefined part of the behavior.

Nor will your program waste any cycles decrementing the retain count to 0; the object is going to be deallocated anyway, why bother?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top