可以重用Objective-c指针吗?

时间:2009-12-12 08:58:08

标签: ios iphone objective-c

在一个简单的基于视图的项目中,我使用以下代码在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?

谢谢。

1 个答案:

答案 0 :(得分:11)

它正在崩溃,因为当你做

delegate.gObj = p2;

在代理的setGObj方法内部,在保留新值之前释放旧值gObj。

所以而不是

[delegate.gObj release];

当你完成p1时你想做

delegate.gObj = nil;

不仅会释放p1,还会告诉代表放手。