如何动态添加类方法?

ma1*_*w28 16 objective-c objective-c-runtime

使用Objective-C Runtime,如何将方法添加+layerClass到私有UIGroupTableViewCellBackground类(而不是其超类UIView)?注意:这仅用于测试(查看如何UITableViewStyleGrouped设置单元格backgroundView&selectedBackgroundView).

ma1*_*w28 18

要动态添加类方法而不是实例方法,请使用object_getClass(cls)获取元类,然后将方法添加到元类.例如:

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);
    });
}
Run Code Online (Sandbox Code Playgroud)

您可以通过将+layerClass方法添加到类别UIGroupTableViewCellBackground和使用转发类定义(即@class UIGroupTableViewCellBackground,使其进行编译)来更轻松地完成此操作.