继承:限制而不是扩展? [英] Inheritance: Restricting rather than extending?

查看:120
本文介绍了继承:限制而不是扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个UIView子类。您定义了一个init方法myInitWithFrame:... andWhatNot:...。您知道您不会使用从UIView ever 继承的init方法,并且您的自定义init方法会执行一些重要的自定义初始化,因此您希望强制客户端类永远不要使用继承的initWithFrame方法。

Suppose you have a UIView subclass. You define an init method "myInitWithFrame: ... andWhatNot:...". You know you won't be using the init method inherited from UIView ever and your custom init method does some vital custom initialising so that you want to force client classes to never use the inherited initWithFrame method.

是否可以隐藏从UIView继承的标准initWithFrame方法?

Is it possible to hide the standard initWithFrame method that was inherited from UIView?

推荐答案

实际上,可以获取有关在子类上调用方法的编译时警告。使用 __属性((不建议使用))属性。如果您希望人们使用 -initWithPizza:而不是 -initWithFrame:,请执行以下操作:

Actually, you can get compile-time warnings about calling a method on a subclass. Use the __attribute((deprecated)) attribute. If you want people to use -initWithPizza: instead of -initWithFrame:, do this:

@interface MyView : UIView
- (id)initWithPizza:(MyPizza *)pizza;
@end

@interface MyView (Deprecations)
- (id)initWithFrame:(CGRect)frame __attribute((deprecated("Use initWithPizza: instead")));
@end

放置 -initWithFrame:声明在一个单独的类别中是必要的,以避免Xcode抱怨您在标头中声明了方法但没有实现它。既然你只是从超类继承它,那很好;你根本没有 来实现它。但是如果你想实现它来抛出异常,或者使用默认参数调用 -initWithPizza:,那很好。

Putting the -initWithFrame: declaration in a separate category is necessary to avoid Xcode complaining that you declared the method in the header but didn't implement it. Since you're just inheriting it from the superclass, that's fine; you don't have to implement it at all. But if you want to implement it to throw an exception, or call through to -initWithPizza: with a default argument, that's fine.

当然,这不会阻止UIKit调用 -initWithFrame:如果它已经这样做了。但如果你能保证不会发生,那你就没事了。

Of course, this won't stop UIKit from calling -initWithFrame: if it was already going to do so. But if you can guarantee that won't happen, then you're fine.

这篇关于继承:限制而不是扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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