A question about the order of passing messages to super


#1

Hi,

On page 115 of the text (In “Lifecycle of a view controller”) one sees the revised methods of viewDidUnload and dealloc. In the first one, [super viewDidUnload] is called (which I believe in this case does nothing) BEFORE one does the local stuff. However in dealloc, [super dealloc] is the last line of the method.

In looking through the text, I detect the following:

  1. in init methods, send init to super first.
  2. in dealloc methods, send dealloc to super last.

(those both make sense to me)

  1. in all other cases, if you feel you need to send a message to super do it first (???)

Are these the general rules?

Thanks

Dave


#2
  1. Yes, there are very rare circumstances where you would do some work before you call the superclasses designated initializer, but for the most part you always call the super init first. (An example of a rare circumstance: you have a UIView subclass that must always be a certain size, you would make changes to the frame rectangle passed in to initWithFrame: before you call the super’s implementation. UISwitch does this.)

  2. Yes, you must call [super dealloc] at the end of a dealloc method. Eventually, dealloc makes its way up to NSObject’s implementation, which actually frees the memory allocated for this instance. You could imagine what would happen if you freed the memory for “self” and then started trying to play with “self’s” instance variables.

  3. Every other method is context-sensitive - you have to think about what you are trying to accomplish. A superclass’ implementation isn’t some magic incantation, it’s a chunk of code - call it when you want to run the code in the superclass’ implementation. The “rule” is that if you are relying on the superclass to do something first, you should call the superclass’ implementation first. If you need the superclass to wait until you do some work first, then you can call the superclass’ implementation at the end. You could also call it somewhere in the middle if you wanted to. Either way, no real rule governing this one.