views:

75

answers:

1

Here is what I try to do: In a simple view-based project, I added a variable in appDelegate

NSObject* gObj;

@property(noatomic,retain) NSObject* gObj;

@synthesize gObj;

then in the testviewController.m viewDidLoad() I added such test code:

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?

thanks a lot.

+11  A: 

it's crashing because when you do

delegate.gObj = p2;

internally the setGObj method of your delegate releases the old value of gObj before retaining the new value.

so instead of

[delegate.gObj release];

when you're done with p1 you want to do

delegate.gObj = nil;

which will not only release p1 but also tell the delegate to let go of it.

David Maymudes