我有一个A类和一个B类,它是A的子类。两者都有以下方法:
-(void)anotherMethod{
// implementation of A or B
}
-(void)aMethod{
@try{
[super aMethod];
}
@catch(NSException *e){
}
[self anotherMethod];
}
现在:如果我致电[instanceOfClassB aMethod]
,A的[self anotherMethod]
实施中包含的指令aMethod
会调用B anotherMethod
(因为它被覆盖)而不是A的一个。如何让A实现aMethod
调用A的anotherMethod
实现?
答案 0 :(得分:0)
试试这个:
if ([self isKindOfClass:[ClassB class]]) {
[super anotherMethod];
} else {
[self anotherMethod];
}
答案 1 :(得分:0)
这可以帮到你: 这个人和你的问题一样。
Objective-c: Calling [self message] on a base class is invoking the descendant method
答案 2 :(得分:0)
解决方案是在调用super之前(以及之后)调用方法,以便用超类1替换子类实现。它需要“黑客”运行时,这是正确的,但我没有找到比这更简单的东西。它有效。