如何动态添加类方法? [英] How to dynamically add a class method?

查看:73
本文介绍了如何动态添加类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

UIKIT_STATIC_INLINE Class my_layerClass(id self, SEL _cmd) {返回 [MyLayer 类];}+(无效)初始化{静态 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,让它编译.<​​/p>

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

解决方案

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.

这篇关于如何动态添加类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆