开发者

Does it matter when super is called in dealloc?

- (void)dealloc {
    [supe开发者_如何学Cr dealloc];
    [receivedData release]; receivedData = nil;
}

or

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


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];
}


Yes. Last. Always.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜