views:

127

answers:

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

or

- (void)dealloc {
    [receivedData release]; receivedData = nil;
    [super dealloc];
}
+13  A: 

Yes. Last. Always.

Steven Noyes
When you use [super dealloc]; base object is destroyed. If you use some data declared in base object it will result in a crash. You should call it last
Felics
+11  A: 

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];
}
Barry Wark
thanks for the descriptive answer!just curious, can this cause a KERN_PROTECTION error or KERN_INVALID_ADDRESS?
Sheehan Alam
@Sheehan Alam: NSObject's `dealloc` frees the object. Accessing `self` after it's gone through that is just like accessing any freed memory — it could cause an error or it could do much weirder things.
Chuck
@Sheeham, Yes. That is a possibility.
Barry Wark
To be specific, you want to release your own stuff. You would never want to do something like [myIvarThing dealloc], but I'm sure that's what you meant :)
Andrew Pouliot
+3  A: 

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.

Jared P