【发布时间】:2012-04-02 08:14:13
【问题描述】:
这是我的代码:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *string = [[NSString alloc] initWithFormat:@"s"];
[string autorelease];
NSLog(@"retainCount of string is %d", [string retainCount]);
[pool release];
NSLog(@"retainCount of string is %d", [string retainCount]);
当我试图理解自动释放和释放时,我很困惑。 如果使用[string autorelease],在向pool发送release消息后,string的retainCount仍然是1。但是用[string release]替换[string autorelease],最后string的retainCount将为0。我对autorelease的了解是“通过向其发送自动释放消息将对象添加到当前自动释放池以供以后释放”。为什么我向它发送了一条自动释放消息并释放池,我仍然可以访问该对象。
【问题讨论】:
-
retainCount 永远不能返回零。向释放的对象发送消息会产生未定义的行为。
标签: objective-c memory-management nsautoreleasepool