Creating an abstract class in Objective-C

前端 未结 21 2753
感情败类
感情败类 2020-11-22 15:44

I\'m originally a Java programmer who now works with Objective-C. I\'d like to create an abstract class, but that doesn\'t appear to be possible in Objective-C. Is this poss

21条回答
  •  清歌不尽
    2020-11-22 16:08

    (more of a related suggestion)

    I wanted to have a way of letting the programmer know "do not call from child" and to override completely (in my case still offer some default functionality on behalf of the parent when not extended):

    typedef void override_void;
    typedef id override_id;
    
    @implementation myBaseClass
    
    // some limited default behavior (undesired by subclasses)
    - (override_void) doSomething;
    - (override_id) makeSomeObject;
    
    // some internally required default behavior
    - (void) doesSomethingImportant;
    
    @end
    

    The advantage is that the programmer will SEE the "override" in the declaration and will know they should not be calling [super ..].

    Granted, it is ugly having to define individual return types for this, but it serves as a good enough visual hint and you can easily not use the "override_" part in a subclass definition.

    Of course a class can still have a default implementation when an extension is optional. But like the other answers say, implement a run-time exception when appropriate, like for abstract (virtual) classes.

    It would be nice to have built in compiler hints like this one, even hints for when it is best to pre/post call the super's implement, instead of having to dig through comments/documentation or... assume.

    example of the hint

提交回复
热议问题