How to dynamically add a class method?
Try this magic:
#include <objc/runtime.h>
+ (void)load {
class_addMethod(objc_getMetaClass("UIGroupTableViewCellBackground"),
@selector(layerClass), (IMP)my_layerClass, "@:@");
}
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.