Why do I have to call super -dealloc last, and not first?

correct example:

- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}

wrong example:

- (void)dealloc {
    [super dealloc];
    [viewController release];
    [window release];
}

Althoug in alsmost all other cases when overriding a method I would first call the super's method implementation, in this case apple always calls [super dealloc] in the end. Why?


Solution 1:

Its just a guideline. You can call other instructions after [super dealloc]. however you can not access variables of the superclass anymore because they are released when you call [super dealloc]. It is always safe to call the superclass in the last line.

Also KVO and depended (triggered) keys can produce side effects if they are depended of already released member variables.

Solution 2:

I don't know anything about programming for the iPhone, but I would assume that it is for the same reason that destructors need to be called in reverse order. You want to make sure that all your 'garbage' is cleaned up before calling your superclass. If you do it the other way around things can get messy. For instance, if your destructor needs to access memory that the super destructor has already freed:

class X {
    private Map foo;

    function __construct() {
        foo = new Map();
    }

    function __destruct() {
        foo.free;
    }
}

class Y extends X {
    function __construct() {
        super.__construct();
        map.put("foo", 42);
    }

    function __destruct() {
        super.__destruct();
        if (map.containsKey("foo")) {    // boooooooooom!
            doSomething();
        }
    }
}

You may not encounter this problem in your code, because "you know what you're doing", but it is a safer and overall better practice not to do such things.