Creating an abstract class in Objective-C

前端 未结 21 2660
感情败类
感情败类 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:06

    In Xcode (using clang etc) I like to use __attribute__((unavailable(...))) to tag the abstract classes so you get an error/warning if you try and use it.

    It provides some protection against accidentally using the method.

    Example

    In the base class @interface tag the "abstract" methods:

    - (void)myAbstractMethod:(id)param1 __attribute__((unavailable("You should always override this")));
    

    Taking this one-step further, I create a macro:

    #define UnavailableMacro(msg) __attribute__((unavailable(msg)))
    

    This lets you do this:

    - (void)myAbstractMethod:(id)param1 UnavailableMacro(@"You should always override this");
    

    Like I said, this is not real compiler protection but it's about as good as your going to get in a language that doesn't support abstract methods.

提交回复
热议问题