Search code examples
objective-cobjective-c-categoryoverriding

Call super in overridden class method


I want to add a new custom UIButtonType to the UIButton class via a category like so:

enum {
    UIButtonTypeMatteWhiteBordered = 0x100
};

@interface UIButton (Custom)

+ (id)buttonWithType:(UIButtonType)buttonType;

@end

Is it possible to get the super implementation of that overridden method somehow?

+ (id)buttonWithType:(UIButtonType)buttonType {
    return [super buttonWithType:buttonType];
}

The code above is not valid since super refers to UIControl in this context.


Solution

  • No, this is not possible when you use a category to augment a class' functionality, you are not extending the class, you are actually wholly overriding the existing method, you lose the original method completely. Gone like the wind.

    If you create a subclass of UIButton, then this is totally possible:

    enum {
        UIButtonTypeMatteWhiteBordered = 0x100
    };
    
    @interface MyCustomButton : UIButton {}
    
    @end
    
    @implementation MyCustomButton 
    
    + (id)buttonWithType:(UIButtonType)buttonType {
        return [super buttonWithType:buttonType]; //super here refers to UIButton
    }
    
    @end