objective-c - 为什么我们使用 [super dealloc] 而不是 [self dealloc] 或 [object dealloc]

您的问题实际上是一个更通用的问题,可以从dealloc问题中删除。

覆盖方法以及何时应该调用super.

有时,当您进行子类化时,您会覆盖现有方法。有时你想利用那个方便的时间来执行一些行为,有时你想阻止父母做某事并改变行为。

- (void)methodOne {

// don't let silly parent class do method one stuff

// do my stuff …

}

- (void)methodTwo {

// let parent perform his behavior first

[super methodTwo];

// do my stuff …

}

- (void)methodThree {

// do my stuff …

// let parent do his stuff after I have

[super methodThree];

}

- (void)methodFour {

// it's not common, but you might want to split your stuff with a call to

// super - this usually involves knowledge of what super is up to

// do some stuff …

[super methodFour];

// do my stuff …

}

许多方法/类的文档(请参阅 UIView 和 NSManagedObject)可能会说明您是否可以或应该或不应该覆盖方法。好的文档会告诉你什么时候应该调用 super。

调用时[super dealloc],您应该在释放您持有的资源后最后调用它。(因为您可能引用的其他内存可能会被您的父类释放)。

另一个经常调用的super是 init 方法。如果你实现了一个 init 方法,你应该重写父级的“指定初始化器”,你应该从你的调用 super 。

@implementation CustomViewController

- (id)init {

return [super initWithNibName:@"CustomView" bundle:nil];

}

- (id)initWithNibName:(NSString *)name bundle:(NSBundle *)bundle {

return [self init];

}

//…

这种常见模式可防止任何人使用不正确的 nib 文件加载您的类。(这可能需要也可能不需要,这是另一个问题。)

如果碰巧有其他初始化器,根据定义,它们应该调用它们指定的初始化器。因此,如果 UIView 要添加一个initWithNibName:方法,它可能会调用[self initWithNibName:name bundle:nil]该方法,然后将其“捕获”并重定向到您想要的初始化程序。

友情链接