开发者

Few questions: Lifecycle of UIViewController; release vs setting to nil

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 t开发者_StackOverflowo 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?


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.


pointer = nil; // just clears the variable in which you store the pointer, but does not free memory.

[pointer release]; // just frees the object (memory), but does not clear the variable used to point to it.

self.pointer = nil; // sets the variable to nil.  Also releases the object ONLY if pointer is a @property(retain) ivar.

One easy way to see when various methods are called is to do this in your UIViewController:

- (void)viewDidLoad
{
    NSLog(@"MyViewController::viewDidLoad");
    [super viewDidLoad];
    // the rest of your viewDidLoad code, here.
}

// Etc., for the other methods of interest.

NOTE: much can be gleaned from overriding retain & release to log and then following along in the debugger.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜