Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to release the ivar and set the synthesized ivar to nil at the same time?

Tags:

objective-c

I have seen code (probably Apple's own sample code) written in such a way where it releases the ivar in dealloc and setting the property in viewDidUnload.

e.g.

- (void)viewDidUnload
{
  self.navigationController = nil;
}

- (void)dealloc
{
   [_navigationController release];
}

Why do them in two places? Also, why set nil in one and release in another. It seems that self.property = nil would just take care of everything since it would release and set the ivar to nil.

like image 603
Boon Avatar asked Jun 16 '09 21:06

Boon


2 Answers

You're right: you can indeed do self.property = nil everywhere, including dealloc. The only downside is that if the setter method does anything more complicated than just releasing the ivar, you might end up trying to access other fields that have already been released, etc.

As for why you also release the outlet in viewDidUnload, that's a memory optimization. Since the stuff you release in viewDidUnload are things that will be reinstantiated when the view is loaded again, releasing them there frees up memory in low-memory situations.

like image 151
Daniel Dickison Avatar answered Oct 05 '22 02:10

Daniel Dickison


Apple recomments that you not call setters in the init and especially dealloc routines.

This is due to the fact that the object is only partially set up at this time, and setters could have observers attached to them, or could be overridden by subclasses, and otherwise have undesirable affects during dealloc, or could be confused during init with a partially configured object.

Hence, you normally use:

_navigationController = [[NavController alloc] init];

style code in your init routine,

[_navigationController release];

style code in your dealloc, and setters in other code where the object is known to be fully complete.

Some cases to consider:

  • Subclass overrides setNavigationController and references its own ivars allocated by init. Crash on init.
  • Subclass overrides setNavigationController and references its own ivars released in dealloc. Crash on dealloc.
  • Subclass overrides setNavigationController and redraws some parts of the screen. Pointless waste of cycles, or glitchy display.
  • Other objects being deallocated at the same time observe navigationController and those observers fire during dealloc
  • etc
like image 35
Peter N Lewis Avatar answered Oct 05 '22 04:10

Peter N Lewis