Creating an abstract class in Objective-C

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

    Just riffing on @Barry Wark's answer above (and updating for iOS 4.3) and leaving this for my own reference:

    #define mustOverride() @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"%s must be overridden in a subclass/category", __PRETTY_FUNCTION__] userInfo:nil]
    #define methodNotImplemented() mustOverride()
    

    then in your methods you can use this

    - (void) someMethod {
         mustOverride(); // or methodNotImplemented(), same thing
    }
    



    Notes: Not sure if making a macro look like a C function is a good idea or not, but I'll keep it until schooled to the contrary. I think it's more correct to use NSInvalidArgumentException (rather than NSInternalInconsistencyException) since that's what the runtime system throws in response to doesNotRecognizeSelector being called (see NSObject docs).

提交回复
热议问题