Search code examples
objective-ciosdelegatesdeallocretaincount

Objective c - call method on dealloc delegate


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?


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