可以重用Objective-c指针吗?

0 iphone objective-c ios

在一个简单的基于视图的项目中,我appDelegate使用以下代码在我的文件中添加了一个变量:

NSObject* gObj;

@property(noatomic,retain) NSObject* gObj;

@synthesize gObj;
Run Code Online (Sandbox Code Playgroud)

然后,在我的testviewController.mviewDidLoad方法中,我添加了以下测试代码:

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?
Run Code Online (Sandbox Code Playgroud)

谢谢.

Dav*_*des 11

它崩溃了,因为当你这样做

delegate.gObj = p2;
Run Code Online (Sandbox Code Playgroud)

在内部,委托的setGObj方法在保留新值之前释放旧值gObj.

而不是

[delegate.gObj release];
Run Code Online (Sandbox Code Playgroud)

当你完成p1时,你想做

delegate.gObj = nil;
Run Code Online (Sandbox Code Playgroud)

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