强制子类重写方法

ary*_*axt 23 oop inheritance overriding objective-c

我怎样才能使任何继承自我的基类的类被强制覆盖特定的方法?我不想使用协议,因为这不会使此行为自动化.

@interface MyBaseClass : NSObject 
{
}

- (void)performAnAction;

@end

@implementation MyBaseClass

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

@end
Run Code Online (Sandbox Code Playgroud)

Lil*_*ard 46

你是什​​么意思,强迫他们覆盖它?如果你只是像这样实现父方法:

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

然后,如果子类无法覆盖它,它将在运行时抛出异常.不幸的是,没有办法在编译时强制执行此操作.

  • @JamesBillingham:任何编写调用`[super performAction]`的子类的人都会很快学会在这种情况下不合适.理想情况下,类头将记录任何实现者不应该调用`super`. (3认同)