子类应该在直接超类中调用指定的初始值设定项吗? [英] Should subclasses call the designated initializer in the immediate super class?

查看:94
本文介绍了子类应该在直接超类中调用指定的初始值设定项吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过一些示例代码让我想知道在超类中调用指定的初始化程序。假设我有一些代码:

I've seen some sample code which has got me wondering about calling the designated initializer in the super classes. Say I have some code this:

@interface NewTableViewCell : UITableViewCell {
}
@end

@implementation NewTableViewCell 
- (id) initWithFrame: (CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Do some stuff
    }
return self;
}
@end

请注意 initWithFrame UIView 的指定初始值设定项,而不是 UITableView 。该代码是否应始终调用 [UITableViewCell initWithStyle:reuseIdentifier:] ,还是取决于编码器的意图?

Note that initWithFrame is the designated initializer for UIView, not UITableView. Should this code always be calling [UITableViewCell initWithStyle:reuseIdentifier:], or does it depend on the coder's intent?

推荐答案

当子类化时,指南是指定的初始化程序必须调用其超类指定的初始化程序。

When subclassing, the guideline is that the designated initializer has to call its super class' designated initializer.

另一个指导原则是子类需要覆盖超类的指定初始化程序以调用新的指定初始化程序。

Another guideline is that the subclass needs to override the superclass' designated initializer to call the new designated initializer.

如果 UITableViewCell 遵循本指南(它确实;我在一个类别的帮助下测试过),它覆盖了它的超类'指定的初始化器( UIView initWithFrame:)调用新的指定初始值设定项( initWithStyle:reuseIdentifier:)。因此,如果在 UITableViewCell 上调用 initWithFrame:,它将调用 initWithStyle:reuseIdentifier:,反过来会在 super 上调用 initWithFrame: UIView )。

If UITableViewCell follows this guideline (and it does; I tested with the help of a category), it overrides its superclass' designated initializer (UIView's initWithFrame:) to call the new designated initializer (initWithStyle:reuseIdentifier:). Therefore, if you call initWithFrame: on UITableViewCell it will call initWithStyle:reuseIdentifier:, which in turn will call initWithFrame: on super (UIView).

因此,它需要一个额外的方法调用,但它最终将通过 initWithStyle:reuseIdentifier:

Therefore, it will need an additional method call but it will eventually go through initWithStyle:reuseIdentifier:.

同样,最佳做法是指定的初始化程序必须调用超类的指定初始化程序和任何其他未指定的初始化程序初始化程序必须调用指定的初始化程序。来自指定初始化程序

Again, the best practice is that the designated initializer has to call the super class' designated initializer and any other initializer that isn't the designated initializer has to call the designated initializer. From "The Designated Initializer":


一般原则:指定的初始值设定项一个类必须通过超级消息调用超类中的指定初始值设定项。

General principle: The designated initializer in a class must, through a message to super, invoke the designated initializer in a superclass.

指定的初始值设定项通过消息链接到super,而其他初始化方法是通过消息链接到指定的初始化者。

Designated initializers are chained to each other through messages to super, while other initialization methods are chained to designated initializers through messages to self.

这篇关于子类应该在直接超类中调用指定的初始值设定项吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆