如何避免子类无意中重写超类私有方法

sam*_*m-w 6 objective-c objective-c-category class-extensions

我正在写一个图书馆,可能会被那些不是我的人使用.

假设我写了一堂课:

InterestingClass.h

@interface InterestingClass: NSObject
- (id)initWithIdentifier:(NSString *)Identifier;
@end
Run Code Online (Sandbox Code Playgroud)

InterestingClass.m

@interface InterestingClass()
- (void)interestingMethod;
@end

@implementation InterestingClass
- (id)initWithIdentifier:(NSString *)Identifier {
  self = [super init];
  if (self) {
    [self interestingMethod];
  }
  return self;
}

- (void)interestingMethod {
  //do some interesting stuff
}
@end
Run Code Online (Sandbox Code Playgroud)

如果某人稍后使用该库并决定创建一个子类InterestingClass

InterestingSubClass.h

@interface InterestingSubClass: InterestingClass
@end
Run Code Online (Sandbox Code Playgroud)

InterestingSubClass.m

@interface InterestingSubClass()
- (void)interestingMethod;
@end

@implementation InterestingSubClass
- (void)interestingMethod {
  //do some equally interesting, but completely unrelated stuff
}
@end
Run Code Online (Sandbox Code Playgroud)

未来的库用户可以从公共接口看到这initWithIdentifier是超类的方法.如果他们覆盖此方法,他们可能会(正确地)假设superclass应该在子类实现中调用该方法.

但是,如果他们定义了一个方法(在子类私有接口中),该方法无意中与超类"私有"接口中的无关方法同名?如果没有它们读取超类私有接口,他们就不会知道它们不仅仅是创建一个新方法,而且还覆盖了超类中的某些东西.子类实现可能最终被意外调用,并且在调用方法时超类期望完成的工作将无法完成.

我读过的所有SO问题似乎都暗示这就是ObjC的工作方式,并且没有办法绕过它.是这种情况,还是我可以做些什么来保护我的"私人"方法不被覆盖?

或者,有没有办法从我的超类中调用方法的范围,所以我可以确定将调用超类实现而不是子类实现?

Cla*_*ges 3

AFAIK,您能期望的最好的结果就是声明重写必须调用 super。您可以通过将超类中的方法定义为:

- (void)interestingMethod NS_REQUIRES_SUPER;
Run Code Online (Sandbox Code Playgroud)

这将在编译时标记任何不调用 super 的覆盖。