views:

54

answers:

2

In my current test I have a class "PlanetClass" that inherits from "celestialClass". My question is when I release my "PlanetClass" object it goes through both dealloc methods, firstly releasing the Planet object and then the Celestial object. I added the dealloc to celestial to make sure I could release the iVar "bodyName", I think I have this right I just wanted to check?

@implementation CelestialClass
- (NSString *)bodyName {
    return [[bodyName retain] autorelease];
}
- (void)setBodyName:(NSString *)newBodyName {
    if (bodyName != newBodyName) {
        [bodyName release];
        bodyName = [newBodyName copy];
    }
}
- (void) dealloc {
    NSLog(@"_deal_CB: %@", self);
    [bodyName release];
    bodyName = nil;
    [super dealloc];
}
@end

@implementation PlanetClass
- (int *)oceanDepth {
    return oceanDepth;
}
- (void)setOceanDepth:(int *)value {
        oceanDepth = value;
}
- (void) dealloc {
    NSLog(@"_deal: %@", self);
    [super dealloc];
}
@end

cheers -gary-

+3  A: 

What happens is any instance of the Planet class will call dealloc there, then it will call

[super dealloc];

Which calls the celestial class dealloc, allowing bodyName to be released.

So basically, yes, you do have it right.

bobDevil
Thank you, just for reference does "Celestial" [super dealloc] ultimately deallocate its parent NSObject too? or does it work different for that?
fuzzygoat
Yes it does. As long as every subclass plays nicely and calls [super dealloc] at the end of the dealloc, the NSObject will get it's dealloc method called.
bobDevil
+1  A: 

There is no magic with -dealloc.

When you invoke [super dealloc], it works exactly like any other call to a super class in any other method.

Which is exactly why the call to [super dealloc] must always be the last line in a dealloc method. If it wasn't, you'd call through to NSObject's -dealloc, which would deallocate the object, return from the -dealloc, and then try to do something with self or self's instance variables, leading to a crash.

So, yes, your code -- as written -- is correct.

bbum