【发布时间】:2009-05-25 18:32:58
【问题描述】:
我正在阅读memory management 的苹果文档,遇到了一些我不明白的东西。基本上,我不明白为什么不需要通过“getter”方法保留实例变量。我写了这个小程序来看看会发生什么。我以为会发生崩溃,但我显然错过了一些东西。
// main.m
// Test
//
#import <Foundation/Foundation.h>
#import "Test.h"
int main(int argc, char *argv[])
{
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
//Initialize the test object
Test *t = [[Test alloc] init];
//Set the value to 5
[t setMyNum:[NSNumber numberWithInt:5]];
//Save a temp number that points to the original number
NSNumber *tempNum = [t myNum];
//release old number and retain new
[t setMyNum:[NSNumber numberWithInt:7]];
//Shouldn't this crash because tempNum is pointing to a deallocated NSNumber???
NSLog(@"the number is %@",tempNum);
[p drain];
return 0;
}
tempNum 不是指向一个被释放的对象吗??
感谢所有帮助。
编辑这是getter和setter方法中的代码
#import "Test.h"
@implementation Test
- (void)setMyNum:(NSNumber *)newNum {
[newNum retain];
[myNum release];
myNum = newNum;
}
-(NSNumber *)myNum {
return myNum;
}
@end
如您所见,我正在对旧对象调用 release。
编辑这是建议的,我认为 tempNum 仍然存在的原因是因为它还没有从池中自动释放。但是即使将 [pool drain] 移动到 NSLog 消息之前的右侧,也没有崩溃???很奇怪。
【问题讨论】:
标签: objective-c memory-management