开发者

Question regarding subclassing

开发者 https://www.devze.com 2023-01-08 20:05 出处:网络
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 requ

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> ?


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.


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];
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消