我正在写一个图书馆,可能会被那些不是我的人使用.
假设我写了一堂课:
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的工作方式,并且没有办法绕过它.是这种情况,还是 …
Mountain Lion引入了新的API,其中一些我们已经在项目中作为类别实现.
对于例子,我们有一个类别NSColor+CGColorAdditions是实现CGColor和colorWithCGColor:为NSColor.Mountain Lion中添加了这些方法.
理想情况下,如果客户端操作系统比Mountain Lion更旧,我们希望使用这些类别,如果是Mountain Lion,则不使用它们.我们应该怎么做?还是有更好的选择吗?