Search code examples
objective-cdeallociboutlet

Is it required to set outlets variables to nil in dealloc (even after IOS 3.0)?


In apple's <Memory Management> Document when talking about Outlets.

It says

in your custom view controller class you can implement viewDidUnload to invoke your accessor methods to set outlets to nil.

I can understand this, since in this case invoke the accessor methods to set nil will release the object and set the pointer to nil can prevent an access to invalid point which may cause crash.

But after that , it says:

Note: On iOS prior to 3.0, the viewDidUnload method is not available. Instead you should set outlets to nil in setView:, as illustrated in this example:

- (void)setView:(UIView *)aView {
    if (!aView) { // View is being set to nil.
        // Set outlets to nil, e.g.
        self.anOutlet = nil;
    }
    // Invoke super's implementation last.
    [super setView:aView];
}

In addition, because of a detail of the implementation of dealloc in UIViewController, you should also set outlet variables to nil in dealloc:

- (void)dealloc {
    // Release outlets and set outlet variables to nil.
    [anOutlet release], anOutlet = nil;
    [super dealloc];
}

1)Why even in dealloc we need to set nil? (I think dealloc is the last step of a object life-cycle, nobody else can access the outlet through this object.)

2)Do we still need to set nil in iOS 3.0 or later?( I found the code Xcode automatically generateed don't set nil to outlet varibles, only release them.)


Solution

  • nope, you don't need to set your outlets to nil in dealloc. Just make sure you are releasing them.