0

在我目前的测试中,我有一个继承自“celestialClass”的类“PlanetClass”。我的问题是当我释放我的“PlanetClass”对象时,它会通过两个 dealloc 方法,首先释放 Planet 对象,然后释放 Celestial 对象。我将 dealloc 添加到 celestial 以确保我可以释放 iVar“bodyName”,我想我有这个权利,我只是想检查一下?

@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

干杯-加里-

4

2 回答 2

3

发生的事情是 Planet 类的任何实例都会在那里调用 dealloc,然后它会调用

[super dealloc];

其中调用了天体类dealloc,允许bodyName被释放。

所以基本上,是的,你做对了。

于 2009-09-16T21:52:23.017 回答
1

-dealloc 没有魔法。

当您调用[super dealloc]时,它的工作方式与在任何其他方法中对超类的任何其他调用完全相同。

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.

于 2009-09-16T22:38:05.053 回答