Force child classes to override method

ぃ、小莉子 提交于 2019-12-21 03:30:52

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4371626/force-child-classes-to-override-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!