Search code examples
objective-cobjective-c-runtime

How to dynamically add a class method?


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).


Solution

  • 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.