R – Class Instance Release Order

memoryobjective c

This is probably a pretty basic question, but just something that I wanted to make sure I had right in my head. When I release the class instance "newPlanet_001" what is the order of disposal, Am I right in assuming that if the retain count of the object is 1 prior to the release that the instances dealloc method is called first (to release the instance variable "planetName") before continuing to release the class instance as a whole?

(i.e.)

// CLASS
@interface PlanetClass : NSObject {
    NSString *planetName;
}
- (NSString *)planetName;
- (void)setPlanetName:(NSString *)newPlanetName;
@end

// MAIN
int main (int argc, const char *argv[]) {
    PlanetClass *newPlanet_001;
    newPlanet_001 = [[PlanetClass alloc] init];
    [newPlanet release];
}

// DEALLOC
- (void)dealloc {
    [planetName release];
    [super dealloc];
}
@end

cheers -gary-

Best Answer

-[NSObject release] calls -dealloc if the retain count is zero. This allows the object to cleanup any objects it owns before calling [super dealloc] to do the actual deallocation.

If implemented properly, an object will release any objects it owns before calling the super (this them to get deallocated if their retain count is also zero).

An object owns another if it calls alloc, copy or retain on it.