开发者

Force child classes to override method

开发者 https://www.devze.com 2023-01-29 18:02 出处:网络
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.

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消