我正在编写一个库,可能会被其他人使用。
假设我写了一个类:
InterestingClass.h
@interface InterestingClass: NSObject
- (id)initWithIdentifier:(NSString *)Identifier;
@end
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
如果后来有人正在使用该库,并决定创建InterestingClass
的子类,会怎样呢?:
InterestingSubClass.h
@interface InterestingSubClass: InterestingClass
@end
InterestingSubClass.m
@interface InterestingSubClass()
- (void)interestingMethod;
@end
@implementation InterestingSubClass
- (void)interestingMethod {
//do some equally interesting, but completely unrelated stuff
}
@end
未来的图书馆用户可以从公共接口中看到
initWithIdentifier
是超类的一个方法。如果他们覆盖此方法,他们可能会认为(正确地),在子类实现中应调用superclass
方法。然而,如果他们定义了一个方法(在子类的私有接口中)与超类“私有”接口中的一个不相关的方法无意间具有相同的名称呢?如果他们没有阅读超类的私有接口,他们将不知道他们不仅创建了一个新方法,还覆盖了超类的内容。子类实现可能会被意外调用,并且当调用该方法时,超类期望完成的工作将不会完成。
我阅读过的所有SO问题似乎都表明这就是ObjC的工作方式,没有办法避免这种情况。是这样吗,还是我可以做一些事情来保护我的“私有”方法不被覆盖? 或者,是否有一种方法可以限定从我的超类中调用方法,以便我确信将调用超类的实现而不是子类的实现?