Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call super in overridden class method [duplicate]

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.


1 Answers

You can replace the method at runtime with your own custom method like so:

#import <objc/runtime.h>

@implementation UIButton(Custom)

// At runtime this method will be called as buttonWithType:
+ (id)customButtonWithType:(UIButtonType)buttonType 
{
    // ---Add in custom code here---

    // This line at runtime does not go into an infinite loop
    // because it will call the real method instead of ours. 
    return [self customButtonWithType:buttonType];
}

// Swaps our custom implementation with the default one
// +load is called when a class is loaded into the system
+ (void) load
{
    SEL origSel = @selector(buttonWithType:);

    SEL newSel = @selector(customButtonWithType:);

    Class buttonClass = [UIButton class];

    Method origMethod = class_getInstanceMethod(buttonClass, origSel);
    Method newMethod = class_getInstanceMethod(buttonClass, newSel);
    method_exchangeImplementations(origMethod, newMethod);
}

Be careful how you use this, remember that it replaces the default implementation for every single UIButton your app uses. Also, it does override +load, so it may not work for classes that already have a +load method and rely on it.

In your case, you may well be better off just subclassing UIButton.

Edit: As Tyler notes below, because you have to use a class level method to make a button this may be the only way to override creation.

like image 191
Kendall Helmstetter Gelner Avatar answered Sep 06 '26 05:09

Kendall Helmstetter Gelner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!