- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在编写一个库,它可能会被我以外的人使用。
假设我写了一个类:
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
future 的库用户可以从公共(public)接口(interface)看到initWithIdentifier
是父类的一个方法。如果他们覆盖此方法,他们可能会(正确地)假设 superclass
方法应该在子类实现中调用。
但是,如果他们定义的方法(在子类私有(private)接口(interface)中)无意中与父类(super class)“私有(private)”接口(interface)中的不相关方法同名怎么办?如果他们不阅读父类(super class)的私有(private)接口(interface),他们将不会知道他们不仅创建了一个新方法,而且还覆盖了父类(super class)中的某些内容。子类实现可能最终被意外调用,而父类(super class)在调用方法时期望完成的工作将无法完成。
我读过的所有 SO 问题似乎都表明这正是 ObjC 的工作方式,没有办法绕过它。是这种情况吗,或者我可以做些什么来保护我的“私有(private)”方法不被覆盖吗?
或者,是否有任何方法可以限定从我的父类(super class)调用方法的范围,以便我可以确定将调用父类(super class)实现而不是子类实现?
最佳答案
据我所知,您最多只能声明覆盖必须调用 super。您可以通过将父类(super class)中的方法定义为:
- (void)interestingMethod NS_REQUIRES_SUPER;
这将在编译时标记任何不调用 super 的覆盖。
关于objective-c - 如何避免子类无意中覆盖父类(super class)私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14627747/
这个问题已经有答案了: Why do I get "AttributeError: NoneType object has no attribute" using Tkinter? Where did
我有一个列表,我想从中删除没有出现在另一个列表中的项目。我试过以下方法: for w in common: for i in range(1,n): if no
我遇到了一些自定义管理页面触发 Django 管理站点而不是显示我的自定义页面的问题。 我的 urls.py 如下: urlpatterns = patterns('', # ... trim
我尝试使用 href 方法下载 CSV 文件,但是将其设置为 href 标记时数据似乎被 chop 。对于 IE,我使用了 msSaveBlob,它似乎工作正常并且所有数据都已正确下载。
我是一名优秀的程序员,十分优秀!