Objective-c – Override a method via ObjC Category and call the default implementation


When using categories, you can override implementation methods with your own like so:

// Base Class 
@interface ClassA : NSObject 
- (NSString *) myMethod;
@implementation ClassA
- (NSString*) myMethod { return @"A"; }

@interface ClassA (CategoryB) 
- (NSString *) myMethod;
@implementation ClassA (CategoryB)
- (NSString*) myMethod { return @"B"; }

Calling the method "myMethod" after including the category nets the result "B".

What is the easiest way for the Category implementation of myMethod to call the original Class A myMethod? As near as I can figure out, you'd have to use the low level calls to get the original method hook for Class A and call that, but it seemed like there would be a syntactically easier way to do this.

Best Solution

If you want a hackish way to do this that involves mucking with the objective-c runtime you can always use method swizzling (insert standard disclaimers here.) It will allow you to store the different methods as arbitrariliy named selectors, then swap them in at runtime as you need them.