Question

I have an object Person and a protocol PersonDelegate
Person has a @property (assign) id<PersonDelegate> delegate;

somewhere in my code I do:

Person *newPerson = [[Person alloc] init]; 
newPerson.delegate = theDelegate;  
...  
[theDelegate release]; // and dealloc

...

now Person has some new information for the delegate, so I call in Person
[self.delegate doSomething];

But then I'm getting EXC_BAD_ACCESS

Is this because the delegate was already dealloc? How can Person know that his delegate is dealloc?

Was it helpful?

Solution

Your delegate property is not set to retain so it will go bad as soon as you do [theDelegate release];

Normally a delegate is set to assign though to avoid a circular reference. But in that case the delegate itself is normally already keeping a reference to the object it is delegated from.

ie.

Person *newPerson = [[Person alloc] init]; 
[self.people addObject:newPerson];
newPerson.delegate = self;
[newPerson release];

So self.people is retaining all the persons which are created and those persons all point back to self as their delegate

OTHER TIPS

You are assigning your delegate instead of retaining it. Since you release your delegate it is no longer valid in your person object as it was NOT retained by it.

Change your delegate property to :

@property (retain) id<PersonDelegate> delegate;

and dont forget to release it when you dealloc your person object

Assuming you really want assign.... :)

You could save the newPerson as a property and set its delegate to nil before the delegate object is released. You could have a Person object listen for a notification that the delegate is going away and have it set it to nil by itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top