Force child classes to override method

2019-03-22 18:53发布

How can I make it so that any class that inherits from my base class is forced to override a specific method? I don't want to use a protocol, because that wouldn't make this behavior automated.

@interface MyBaseClass : NSObject 
{
}

- (void)performAnAction;

@end

@implementation MyBaseClass

- (void)performAnAction
{
    @throw([NSException exceptionWith...]);
}

@end

2条回答
等我变得足够好
2楼-- · 2019-03-22 19:12

How exactly do you mean, force them to override it? If you simply implement the parent method like so:

- (void)performAction {
    NSAssert(NO, @"The method %@ in %@ must be overridden.",
         NSStringFromSelector(_cmd), NSStringFromClass([self class]));
}

then it'll throw an exception at runtime if the child class fails to override it. Unfortunately there is no way to enforce this at compile-time.

查看更多
在下西门庆
3楼-- · 2019-03-22 19:31

You could just throw an exception. As long as this is well documented, then IMO this is a reasonable use of exceptions since it truly is a programming error.

查看更多
登录 后发表回答