在一个简单的基于视图的项目中,我使用以下代码在appDelegate
文件中添加了一个变量:
NSObject* gObj;
@property(noatomic,retain) NSObject* gObj;
@synthesize gObj;
然后,在我的testviewController.m
viewDidLoad方法中,我添加了以下测试代码:
testAppDelegate* delegate = [[UIApplication sharedApplication] delegate];
NSObject* p1 = [NSObject alloc] init];//the reference count is 1
delegate.gObj = p1;//the reference count of p1 is 2
[p1 release];//the ref of p1 is 1 again
[delegate.gObj release];//the ref of p1 is 0
NSObject* p2 = [NSObject alloc] init]; // a new object
delegate.gObj = p2;//this time the program crash, why? should not the pointer be supposed to be re-used again?
谢谢。
答案 0 :(得分:11)
它正在崩溃,因为当你做
时delegate.gObj = p2;
在代理的setGObj方法内部,在保留新值之前释放旧值gObj。
所以而不是
[delegate.gObj release];
当你完成p1时你想做
delegate.gObj = nil;
不仅会释放p1,还会告诉代表放手。