Question about dealloc and viewDidUnload


#1

Hello,

In the book on page 187 (hard copy 1st edition).

Both the viewDidUnload and the dealloc appear to be freeing up resources.

In my mind the order that you ‘new’ or ‘alloc’ things you ‘delete’ or ‘dealloc’ in the REVERSE order.

In the book it shows the following:

-(void)viewDidUnload
{
[super viewDidUnload];

In all of the dealloc methods the [super dealloc] is always called last. Wouldn’t that rule also apply here as well?

Regards,
Ed


#2

The reason [super dealloc] is called at the end is because NSObject’s implementation of dealloc actually frees the memory for the object itself. Therefore, when you call up to NSObject’s dealloc method, another thread may swoop in and scrape up the memory that object was occupying. That memory contained the pointers to any instance variables that object had. If you tried to send messages to those pointers, you would be accessing bad memory.

In viewDidUnload, the controller object still exists, and therefore, when you call [super viewDidUnload], you are only releasing ivars that belong to the superclass. Then, your override releases any ivars introduced by the subclass. There is no danger here. (Unless you are releasing ivars in the superclass, which you should never do.)