Followup on ownership


#1

In the last section of this chapter on Callbacks and object ownership it states that observers typically remove themselves from the notification centre in dealloc. Does that mean if we add an object as an observer we need to override the dealloc method to remove it?

Also it mentions that if you create an object that is a delegate or datasource then your object should “excuse” itself in dealloc. Does this require an overridden method for dealloc?

Also same question about dealloc for target-action. And what about [super dealloc], wouldn’t you need to call the super classes dealloc once you’d cleared up any observers/delegates/target-actions?


#2

In all three cases, yes. The convention is that if you’re using any of these three callback types, you should implement a -dealloc method in your object to nullify the observer/delegate/target reference. Sometimes they won’t be necessary, but it’s good to be safe.

Except in well-documented cases (such as NSURLConnection and NSTimer, as mentioned in the last paragraph of the chapter), Apple’s API that uses callbacks uses __unsafe_unretained rather than __weak references to observers, delegates and targets. This is so that Apple’s frameworks can remain backward compatible with pre-ARC code. The consequence is that if your object (a button’s target, for example) deallocates before the button’s action is fired, the button’s action may be sent to a vacant garbage memory location where your object previously existed, crashing your application.

This is why it’s recommended to implement a -dealloc method in all three cases to make sure that objects that have observer, delegate or target pointers to you know to leave you alone when you deallocate.

As to the call to -super, that’s done for you now under ARC. In pre-ARC code, you must call [super dealloc] at the bottom of your -dealloc method, but now that line is, for lack of a better word, implied. At compile time, the call to super is inserted for you along with the rest of the memory management code that the compiler adds.


#3

Thanks for the clarification and also the info on [super dealloc].