TheLearner
TheLearner

Reputation: 19507

Order of release and dealloc messages

What is the recommended way of doing this. Should I call super dealloc first or last or doesn't it matter?

- (void)dealloc
{
    [super dealloc];
    [orderNumber release];
    [orderDate release];
}

Also when it comes to overriding methods like didViewLoad - should I call super first or last?

Upvotes: 1

Views: 389

Answers (5)

grahamparks
grahamparks

Reputation: 16296

Regarding viewDidLoad (et al), you do whatever works. If you have stuff you want to happen before the superclass does its thing, then you do it before you call the superclass method, and likewise for stuff you want to happen afterwards.

If you don't know whether your code should run before or after, then it probably doesn't matter.

Upvotes: 0

DerekH
DerekH

Reputation: 860

In this case call the super after you have released all your properties/iVars. For viewDidLoad/willAppear/etc. I usually call the super first. The order matters when your custom class is relying on an object that is created by the super. For the default viewDidLoad this is not the case so it is preference(I believe).

Upvotes: 2

Alex Brown
Alex Brown

Reputation: 42892

The pointers orderNumber and orderDate are held inside your object.

[super dealloc] deallocates your object (aka self).

Once you deallocate your object you must not rely on the things inside it (e.g. orderNumber) having the values they did before you deallocated it.

Therefore, deallocate the members before deallocating the self object.


The opposite holds true for init functions - you can't initialise the pointers until after your object is constructed, so [super init] comes before you initialise the members.

Upvotes: 0

hooleyhoop
hooleyhoop

Reputation: 9198

There is no general rule - you chose to override the method, what does it do? Do you want it to happen before or after your custom implementation?

  • didViewLoad doesn't appear to be a real method.

We know that [super dealloc] destroys the current object completely, so any code that comes after it is wrong. So, in this case, call [super dealloc] last.

Upvotes: 0

Eiko
Eiko

Reputation: 25632

Always call [super dealloc] last or you might easily come into trouble because you're working on a stale object.

With didViewLoad you normally call it before your own code as you want the standard initialization stuff executed before. I've seen examples in Apple's code that don't call the super implementation at all, though, so maybe there's not much going on anyway.

Upvotes: 4

Related Questions