Sheehan Alam
Sheehan Alam

Reputation: 60919

Does it matter when super is called in dealloc?

- (void)dealloc {
    [super dealloc];
    [receivedData release]; receivedData = nil;
}

or

- (void)dealloc {
    [receivedData release]; receivedData = nil;
    [super dealloc];
}

Upvotes: 10

Views: 772

Answers (3)

Jared Pochtar
Jared Pochtar

Reputation: 4985

Yes, [super dealloc] must always be last, as said above, because referencing self or any other internals typically taken for granted will not work, and may crash, as also said above.

An additional reason not said above is that ivars are in the chunk of memory pointed to by self, so if you were to do anything with (like release) those ivars after [super dealloc], you would also be dereferencing freed memory.

I said 'may crash' above, because when you do this incorrectly it tends to actually not crash, which makes sense considering the memory isn't overwritten until it's reused. This makes it all the worse, because you will potentially have a bug that only occurs sometimes, making it extra hard to find in case it does blow up in you face.

Other than that, you're perfectly fine if you're releasing a local variable or whatnot after [super dealloc], and you can, if you really want, do something like

id local = ivar;
[super dealloc];
[local release];

safely, but in the interest of consistency, don't.

In summation, yes, [super dealloc] must be the last thing in -dealloc.

Upvotes: 4

Barry Wark
Barry Wark

Reputation: 107764

Yes, it absolutely maters when [super dealloc] is called. Once [super dealloc] is called, you can no longer rely on the NSObject (or whatever your root class is) machinery to function properly. Afterall, your super-class' -dealloc method should call its superclass' etc. until the root class' -dealloc method is called. At that point, everything that these classes allocate to do their job is potentially gone and you're in undefined territory if you try to use any of it.

Your -dealloc method should always look like

- (void)dealloc
{
   // release my own stuff first

   [super dealloc];
}

Upvotes: 16

Steven Noyes
Steven Noyes

Reputation: 1549

Yes. Last. Always.

Upvotes: 13

Related Questions