gpt4 book ai didi

objective-c - 如何避免子类无意中覆盖父类(super class)私有(private)方法

转载 作者:太空狗 更新时间:2023-10-30 03:44:33 24 4
gpt4 key购买 nike

我正在编写一个库,它可能会被我以外的人使用。

假设我写了一个类:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com