Objective-c – Few questions: Lifecycle of UIViewController; release vs setting to nil

cocoa-touchobjective c

I have a couple of questions relating to UIViewController:

1) When are each of the methods called for UIViewController? Specifically, the difference between viewDidLoad, viewDidUnload, and dealloc.

2) What's the difference, in general, when setting a pointer equal to nil and releasing the pointer? I know that in viewDidUnload you're supposed to set it equal to nil but in dealloc call release.

UPDATE: Sorry, just realized the question is misleading. Instead of dealloc, I meant — when is initWithNibName:bundle: and release called? Just once by IB, right?

Best Answer

Setting a pointer to nil doesn't release the memory that it points to.

When you do something like

self.pointer = nil;

it's usually a case that the property has a retain attribute. When this is the case, setting the property to nil will indirectly cause a

[pointer release];
pointer = nil;

In the case of the view controller methods, viewDidLoad is called when your view is loaded, either from a nib, or programatically. More specifically, it's called just after -loadView is called. You shouldn't need to call loadView manually, the system will do it. The viewDidUnload method is called in the event of a memory warning and your view controller's view is not onscreen. Subsequently, loadView and viewDidLoad will get called again on demand.

The dealloc method, as normal, is called when your object's retain count reaches 0.

Related Topic