关于子类化的问题

发布于 2024-09-10 16:26:03 字数 471 浏览 0 评论 0原文

这可能是以前问过的,但我不知道要搜索什么。这是我现在的层次结构: 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

合久必婚 2024-09-17 16:26:03

听起来您需要 ducktyping。在 Objective C 中,可以通过使用respondsToSelector、performSelector 或NSInitation 来完成。这可以大大简化类层次结构。

It sounds like you need ducktyping. In objective c it can be accomplished by using respondsToSelector, performSelector or NSInvocation. This can simplify a class hierarchy a lot.

玉环 2024-09-17 16:26:03

创建一个从 FirstSubclass 派生的新对象(例如 InBetweenSubClass)并重写 FirstSubclass 的必要方法。然后将 SecondSubclass 更改为从 InBetweenSubClass 而不是 FirstSubclass 派生。

Objective-C 中没有等效的“重写”,您只需实现具有相同签名的方法,并且基类的该方法将被重写。你也可以这样做,如果满足特殊条件,则使用新方法,否则使用基(超)类的方法:

-(void) test
{
    if (self.specialcondition)
    {
        [self newTest];
    }
    else
    {
        [super test];
    }

}

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:

-(void) test
{
    if (self.specialcondition)
    {
        [self newTest];
    }
    else
    {
        [super test];
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文