R – Memory management in Objective-C


#import <Foundation/Foundation.h>

int main (int argc, char const *argv[])
    SampClass *obj=[[SampClass alloc] init];
    [obj release];
    NSLog(@"%i", [obj retainCount]);
    return 0;

Why does this give retainCount of 1, when it should be 0

Best Solution

Do not call retainCount.

Not even in debugging code. And especially not when you are trying to learn how Cocoa's memory management works.

The absolute retain count of an object is not something under your control. Often, the value will be quite unexpected. There may be any number of caches, static allocations (like constant NSStrings), or other internal implementation details within frameworks that make an object's retain count other than what you expect.

The retain count of objects should be thought of entirely in terms of deltas. If you cause the retain count to increase, you must decrease it somewhere if you want the object to be deallocated. Period. End of story.

Trying to think of retain counts in absolute terms will just lead to confusion and wasted hours.

The Cocoa Memory Management Guide explains this rather well.