我已经看到一些示例代码让我想知道在超类中调用指定的初始化程序.说我有一些代码:
@interface NewTableViewCell : UITableViewCell {
}
@end
@implementation NewTableViewCell
- (id) initWithFrame: (CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Do some stuff
}
return self;
}
@end
Run Code Online (Sandbox Code Playgroud)
注意,这initWithFrame是指定的初始化程序UIView,而不是UITableView.这段代码应该始终在调用[UITableViewCell initWithStyle:reuseIdentifier:],还是取决于编码器的意图?
子类化时,指南是指定的初始化程序必须调用其超类的指定初始化程序.
另一个指导原则是子类需要覆盖超类的指定初始化程序以调用新的指定初始化程序.
如果UITableViewCell遵循本指南(并且确实如此;我在类别的帮助下进行了测试),它会覆盖其超类'指定的初始化程序(UIView's initWithFrame:)来调用新的指定初始化程序(initWithStyle:reuseIdentifier:).因此,如果调用initWithFrame:上UITableViewCell,它会调用initWithStyle:reuseIdentifier:,这反过来将调用initWithFrame:上super(UIView).
因此,它需要一个额外的方法调用,但最终会通过initWithStyle:reuseIdentifier:.
同样,最佳实践是指定的初始化程序必须调用超类的指定初始化程序,而不是指定初始化程序的任何其他初始化程序必须调用指定的初始化程序.来自"指定的初始化程序":
一般原则:类中的指定初始值设定项必须通过超级消息调用超类中的指定初始值设定项.
指定的初始化器通过消息链接到super,而其他初始化方法通过消息链接到指定的初始化器.