Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C inheritance; calling overridden method from superclass?

I have an Objective-C class that has a method that is meant to be overridden, which is uses in a different method. Something like this:

@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

However, when I create a SubClass and try to use it, it still calls overrideMe on the BaseClass and crashes due to doesNotRecognizeSelector:. (I'm not doing a [super overrideMe] or anything stupid like that).

Is there a way to get BaseClass to call the overridden overrideMe?

like image 923
Anshu Chimala Avatar asked Dec 25 '10 21:12

Anshu Chimala


1 Answers

What you are describing here should work so your problem is likely elsewhere but we don't have enough information to help diagnose it.

From your description, I'd say either the instance you're messaging is not the class you think it is or you made some typo in your code when declaring the method names.

Run your application under gdb, add a symbolic breakpoint on objc_exception_throw, reproduce your problem. Once your process has stopped on the "doesNotRecognizeSelector" exception, print object description and it's class.

Or log it before calling -overrideMe:

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

like image 168
Julien Avatar answered Nov 09 '22 19:11

Julien