views:

55

answers:

1

If I assign a delegate property from classB to classA from Interface Builder, should I assign an IBOutlet to classB, then in classA dealloc, set the delegate to nil via the outlet? (Assuming classA is the file's owner of the XIB...)

+2  A: 

Short answer: yes.

Regardless of whether you used Interface Builder or not, it is good practice for the delegate to remove itself as the delegating object's delegate as soon as it relinquishes ownership of (i.e., releases) the delegating object. This can be in its dealloc method at the latest but it also can occur at an earlier point.

The reason: Usually, the delegate is some kind of parent object of the delegating object. Very often, delegate and owner of the delegating object are the same object. Because the parent object usually retains the child object, in order to avoid circular references the delegating (i.e., child) object normally does not retain its delegate. In these cases, it could happen that the delegate object gets deallocated while the delegating object is still alive (if some other object has also retained it). If now the delegating object tries to access its delegate (which doesn't exist anymore), the program could crash.

So right before the parent object releases its child object (usually, but not always, in its dealloc method), it should call childObject.delegate = nil;.

Ole Begemann
You shouldn't annull the `delegate` property unless you're actually the delegate: `if ([otherObject delegate] == self) [otherObject setDelegate:nil];`
Jeremy W. Sherman
+1 for Jeremy. Thanks for the correction.
Ole Begemann