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 callrelease 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);
}
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
答案:
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.