Does the order of statements in the dealloc method matter? Does the [super dealloc]
need to be at the top of the method? Does it matter?
Also in e.g. viewDidLoad
. Should [super viewDidLoad]
be at the top of the method?
Deallocates the memory occupied by the receiver.
-dealloc is an Objective-C selector that is sent by the Objective-C runtime to an object when the object is no longer owned by any part of the application. -release is the selector you send to an object to indicate that you are relinquishing ownership of that object.
When you have 3 instances of the object in your code, and you do an [object1 release] on (let's say) the first object, you still have 2 instances left elsewhere, so it isn't called yet. You'll need to release all instances of the object in order for dealloc to be called.
It ABSOLUTELY matters.
What you do depends on whether you're using Automatic Reference Counting (ARC) or manual reference counting.
Manual Release-Retain (MRR) is default memory management for all versions of Mac OS X, and the only way to handle memory until Xcode 4.2.
With MRR, [super dealloc]
should be at the end of your method.
So your code should look like this:
- (void)dealloc
{
[member release];
[super dealloc];
}
The super dealloc actually frees the memory. Think about that. If you access an instance variable after that, like this:
[super dealloc];
[member release];
...it means that the instance variable is potentially invalid. Between the call to super dealloc and the call to member release, theoretically the bytes that stores the member pointer could have been changed to something else!
As Apple explains it in the Memory Management Programming Guide:
The role of the dealloc method is to free the object's own memory, and dispose of any resources it holds, including ownership of any object instance variables.
You do this by disposing of any resources your object holds, and calling [super dealloc]
. Which disposes any objects it holds, and calls its super. And so on, and so on, until eventually the root object marks the memory used by the instance itself as free. By the time [super dealloc]
returns, your instance has been freed. (Of course, the pointers in it are probably valid, but that's an implementation detail you shouldn't rely on.)
Generally, when constructing (or loading) let the super do the work first. When tearing things down, do your work first.
See also:
Automatic Reference Counting (ARC) is the new way of doing memory management introduced in Xcode 4.2. With ARC, the compiler adds memory management code when compiling your application. It has some wrinkles you'll want to read more about before using it (mostly, limited compatibility with older OS versions).
With ARC, you don't (and can't) call [super dealloc]
at all. Instead, [super dealloc]
is called when your dealloc
finishes.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With