-->

How to dynamically add a class method?

2019-03-18 05:43发布

问题:

Using the Objective-C Runtime, how do I add the method +layerClass to the private UIGroupTableViewCellBackground class (not to its superclass, UIView)? Note: This is only for testing (to see how UITableViewStyleGrouped sets cell backgroundView & selectedBackgroundView).

回答1:

To dynamically add a class method, instead of an instance method, use object_getClass(cls) to get the meta class and then add the method to the meta class. E.g.:

UIKIT_STATIC_INLINE Class my_layerClass(id self, SEL _cmd) {
    return [MyLayer class];
}

+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = object_getClass(NSClassFromString(@"UIGroupTableViewCellBackground"));
        NSAssert(class_addMethod(class, @selector(layerClass), (IMP)my_layerClass, "@:@"), nil);
    });
}

You might also be able to do this easier by adding the +layerClass method to a category of UIGroupTableViewCellBackground and using a forward class definition, i.e. @class UIGroupTableViewCellBackground, to get it to compile.



回答2:

Try this magic:

+ (void)load {
        class_addMethod(objc_getMetaClass("UIGroupTableViewCellBackground"), 
                        @selector(layerClass), (IMP)my_layerClass, "@:@"), nil);
    });
}