Objective-C继承;从超类调用重写方法?

时间:2010-12-25 21:29:29

标签: objective-c oop inheritance

我有一个Objective-C类,它有一个意图被覆盖的方法,它在不同的方法中使用。像这样:

@interface BaseClass
- (id)overrideMe;
- (void)doAwesomeThings;
@end

@implementation BaseClass
- (id)overrideMe {
    [self doesNotRecognizeSelector:_cmd];
    return nil;
}
- (void)doAwesomeThings {
    id stuff = [self overrideMe];
    /* do stuff */
}
@end

@interface SubClass : BaseClass
@end

@implementation SubClass
- (id)overrideMe {
    /* Actually do things */
    return <something>;
}
@end

但是,当我创建SubClass并尝试使用它时,它仍会在overrideMe上调用BaseClass并因doesNotRecognizeSelector:而崩溃。 (我没有做[super overrideMe]或类似的任何愚蠢行为。)

有没有办法让BaseClass来调用被覆盖的overrideMe

2 个答案:

答案 0 :(得分:2)

您在此处描述的内容应该有效,因此您的问题可能在其他地方,但我们没有足够的信息来帮助诊断它。

根据您的描述,我会说您发送消息的实例不是您认为的类,或者在声明方法名称时在代码中输入了一些拼写错误。

在gdb下运行你的应用程序,在objc_exception_throw上添加一个符号断点,重现你的问题。一旦您的进程停止在“doesNotRecognizeSelector”异常上,就打印对象描述及其类。

或者在调用-overrideMe之前记录它:

NSLog(@“object:%@ class:%@”,obj,[obj class])

答案 1 :(得分:-1)

BaseClass写一个类别以覆盖该方法。

@interface BaseClass (MyCategory)
- (id) overrideMe;
@end

@implementation BaseClass (MyCategory)
- (id) overrideMe
{
    /* Actually do things */    
    return <something>;
}

@end

现在BaseClass的所有实例都会使用新的实现来响应选择器overrideMe

相关问题