How to dynamically add a class method?

僤鯓⒐⒋嵵緔 提交于 2019-12-03 15:44:06

问题


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:

#include <objc/runtime.h>

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


来源:https://stackoverflow.com/questions/9377840/how-to-dynamically-add-a-class-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!