Creating an abstract class in Objective-C

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

    You can use a method proposed by @Yar (with some modification):

    #define mustOverride() @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"%s must be overridden in a subclass/category", __PRETTY_FUNCTION__] userInfo:nil]
    #define setMustOverride() NSLog(@"%@ - method not implemented", NSStringFromClass([self class])); mustOverride()
    

    Here you will get a message like:

     ProjectName[7921:1967092]  - method not implemented
     ProjectName[7921:1967092] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ ] must be overridden in a subclass/category'
    

    Or assertion:

    NSAssert(![self respondsToSelector:@selector()], @"Not implemented");
    

    In this case you will get:

     ProjectName[7926:1967491] *** Assertion failure in -[ ], /Users/kirill/Documents/Projects/root/ Services/Classes/ViewControllers/YourClass:53
    

    Also you can use protocols and other solutions - but this is one of the simplest ones.

提交回复
热议问题