覆盖指定的超类初始化程序 [英] Override designated initializer of superclass

查看:212
本文介绍了覆盖指定的超类初始化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本有指南的书:

I am reading a book which has a guideline:

如果一个类声明一个与其超类不同的指定初始化器,那么超类的指定初始化器必须被覆盖调用新的指定的初始化器

"If a class declares a designated initializer that is different from its superclass, the superclass’s designated initializer must be overridden to call the new designated initializer"

我理解这个指南换句话说,如果我是子类化我的类形式其超类,我的子类有一个指定的初始化这与des不同。它的父类的初始化器,然后在我的子类中,我必须重写我的超类的指定的初始化器,并在它的内部调用我的子类的指定的初始化器。

As I understand this guideline in other words is that, if I am subclassing my class form its superclass, and my subclass has a designated initializer which is different from des. initializer of its superclass, then in my subclass I must override the designated initializer of my superclass and inside it call the designated initializer of my subclass.

这是真的吗?我们必须这样做吗?谢谢。

Is this true? Do we have to do this all the time? Thank you.

推荐答案

@justin基本上就是这样。

@justin is basically on the point.

Objective-C中的方法是继承的。这意味着如果超类有一个initializer方法(initializers只是方法),并且你的子类没有覆盖它,那么你的子类将继承那个超类的initializer方法。这意味着人们总是可以在你的子类的对象(继承和子类型多态性的基本结果)上调用该超类的初始化器。但这可能不是你期望的。超类的初始化器可能不会执行你的类所需的所有初始化。

Methods in Objective-C are inherited. That means if the superclass has an initializer method (initializers are just methods), and your subclass does not override it, then your subclass will inherit that superclass's initializer method. That means that people can always call that superclass's initializer on an object of your subclass (basic consequence of inheritance and subtype polymorphism). But that might not be what you expected. The superclass's initializer might not do all the initialization that your class needs.

这就是为什么你应该覆盖超类的初始化器。如果你不希望人们对你的类的对象使用初始化器,你应该在该初始化器中抛出一个异常。否则,您应该覆盖它为您的类执行任何适当的初始化。

That's why you should override the superclass's initializer. If you don't want people to use that initializer on an object of your class, you should throw an exception in that initializer. Otherwise, you should override it to do any appropriate initialization for your class.

这篇关于覆盖指定的超类初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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