views:

77

answers:

1

Hi,

I created a simple program to test the retain/release methods in Objective-C memory management. As I understand of ObjC memory management, I expect that a object with retain count = 1 on which I call release get the retain count decremented to zero and then released. But this test program show that after the first release I still get retain count = 1:

// TestClass.h
#import <Cocoa/Cocoa.h>
@interface TestClass : NSObject {
}
@end

// TestClass.m
#import "TestClass.h"
@implementation TestClass
@end

// RetainRelease.m
#import <Foundation/Foundation.h>
#include "TestClass.h"

void dumpRetain(id o);

int main (int argc, const char * argv[]) {
    TestClass *s = [[TestClass alloc] init];
    dumpRetain(s);

    [s release];
    dumpRetain(s);
}

output:

2010-08-13 17:42:45.489 RetainRelease[20933:a0f] NSString - retain count=1
2010-08-13 17:42:45.491 RetainRelease[20933:a0f] NSString - retain count=1

Someone could explain that? Thanks

+8  A: 

Why should it decrement to zero? When you release an object with a retain count of 1, the object is destroyed, so it doesn't have a retainCount anymore. As such, why bother changing something to zero when it's going to go away a couple of nanoseconds later?

Also, don't think about stuff in terms of retainCount. You'll end up killing yourself out of frustration. Instead think about "do I own this object? If I do, do I properly relinquish ownership of this object when I'm done with it?"

If you can answer those questions properly then that's all you need to do.

Dave DeLong
thank you for your answer. I expected it to decrement to zero becouse of this illustration: http://cocoadevcentral.com/images/articles/000094/learnobjectivec-referencecounting.pngWith this code I only trying to demonstrate how the reference counting works at an abstract point of view; I agree with you that thinking about "do I own this object" is much better in the point of view of app programming.
Max
@Max it's true that thinking about it in terms of "when the retainCount hits zero, the object is deallocated" makes it easy to understand what's going on. However, it's implemented as "when the object is released with a retainCount of 1, it's deallocated", because there's no need to ever decrement it to 0. It's an implementation optimization.
Dave DeLong
thank you for your clarification
Max