Objective c 如何动态添加类方法?

Objective c 如何动态添加类方法?,objective-c,objective-c-runtime,Objective C,Objective C Runtime,使用Objective-C运行时,如何将方法+layerClass添加到私有UIGroupTableViewCellBackground类(而不是其超类,UIView)中?注意:这仅用于测试(要查看UITableViewStyleGrouped如何设置单元格backgroundView&selectedBackgroundView)。要动态添加类方法,而不是实例方法,请使用object\u getClass(cls)获取元类,然后将方法添加到元类。例如: UIKIT_STATIC_INLINE

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

要动态添加类方法,而不是实例方法,请使用
object\u 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);
    });
}
通过将
+layerClass
方法添加到
UIGroupTableViewCellBackground
的类别中,并使用前向类定义(即
@class-UIGroupTableViewCellBackground
)将其编译,您也可以更轻松地完成此任务。

试试这个魔术:

#include <objc/runtime.h>

+ (void)load {
    class_addMethod(objc_getMetaClass("UIGroupTableViewCellBackground"), 
        @selector(layerClass), (IMP)my_layerClass, "@:@");
}
#包括
+(空)荷载{
类\u addMethod(objc\u getMetaClass(“UIGroupTableViewCellBackground”),
@选择器(layerClass),(IMP)我的layerClass,“@:”;
}

你是在独处吗?问答?5分钟后youfself发布了答案?@samfisher:这是一件完全合法的事情:Matt只是在向信息库添加信息。谢谢@JoshCaswell在这方面给我启发。。!!还包括