开发者

Doing [obj release] on obj with retainCount=1 does not decrement retainCount to zero

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&开发者_如何学Cgt;
#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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜