关于子类化的问题
这可能是以前问过的,但我不知道要搜索什么。这是我现在的层次结构: NSObject >第一子类>第二子类。但我将在我的应用程序中实现一项新功能,该功能需要在满足特定条件时更改 FirstSubclass 中的一些细节。所以实际上我需要 FirstSubclass 和 SecondSubclass 之间的子类来覆盖 FirstSubclass 的行为。我不需要覆盖 SecondSubclass 本身的内容,但我需要某种 super
来表示我拥有的所有不同的 SecondSubclass 子类。我可以更改 FirstSubclass 中的所有内容以使用“if then statements”,但首先我想确定是否没有其他选择。我需要为此制定一个“协议”吗?就像 SecondSubclass : FirstSubclasslass
中那样?
This is probably asked before but I have no idea what to search for. This is my hierarchy now: NSObject > FirstSubclass > SecondSubclass. But I'm going to implement a new feature in my app which requires changing a few details in FirstSubclass when a certain condition is met. So actually I would need a subclass between FirstSubclass and SecondSubclass to overwrite FirstSubclass' behavior. I do not need to overwrite things in SecondSubclass itself but I need some kind of super
for all different SecondSubclass subclasses I have. I could change everything in FirstSubclass to use "if then statements" but first I wanted to be sure if there wasn't another option. Do I need a "protocol" for this? Like in SecondSubclass : FirstSubclasslass <WeirdThingIDontKnow>
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您需要 ducktyping。在 Objective C 中,可以通过使用respondsToSelector、performSelector 或NSInitation 来完成。这可以大大简化类层次结构。
It sounds like you need ducktyping. In objective c it can be accomplished by using
respondsToSelector
,performSelector
orNSInvocation
. This can simplify a class hierarchy a lot.创建一个从 FirstSubclass 派生的新对象(例如 InBetweenSubClass)并重写 FirstSubclass 的必要方法。然后将 SecondSubclass 更改为从 InBetweenSubClass 而不是 FirstSubclass 派生。
Objective-C 中没有等效的“重写”,您只需实现具有相同签名的方法,并且基类的该方法将被重写。你也可以这样做,如果满足特殊条件,则使用新方法,否则使用基(超)类的方法:
Create a new object that derives from FirstSubclass (say InBetweenSubClass) and overrides the necessary methods of FirstSubclass. Then change SecondSubclass to derive from InBetweenSubClass instead of FirstSubclass.
There is no "override" equivalent in Objective-C, you just implement a method with the same signature and that method of the base class is overridden. You can do something like this as well, if special condition is met, use new method, otherwise use the method of the base (super) class: