美文网首页
Runtime 04 - 应用(动态创建类、交换方法)

Runtime 04 - 应用(动态创建类、交换方法)

作者: 石头89 | 来源:发表于2019-08-18 00:59 被阅读0次

Runtime 04 - 应用(动态创建类、交换方法)

动态创建类

需要创建的类结构如下

// 人的抽象模型
@interface Person : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;

- (void)sayHello;
- (void)run;

@end

@implementation Person

- (void)sayHello {
    NSLog(@"Hi,我是%@,我今年%d了!", self.name, self.age);
}

- (void)run {
    NSLog(@"我跑啊跑啊跑啊跑。。。");
}

@end

// 歌唱家
@protocol Singer

- (void)sing;

@end

// 歌唱明星
@interface Star : Person <Singer>
{
    @public
    NSString *_company;
}
@end

@implementation Star

- (void)sing {
    NSLog(@"la la la so mi ~");
}

@end

动态创建类的示例

先定义一些全局函数,后面用作 Person 类的属性方法:

// 从一个 Class 对象中获取实例变量
#define GetIvar(class, name) class_getInstanceVariable(class, name)

// Person 类 name 属性的 getter
NSString* name(id self, SEL _cmd) {
    return object_getIvar(self, GetIvar([self class], "_name"));
}

// Person 类 name 属性的 setter
void setName(id self, SEL _cmd, NSString *name) {
    return object_setIvar(self, GetIvar([self class], "_name"), name);
}

// Person 类 age 属性的 getter
int age(id self, SEL _cmd) {
    return [object_getIvar(self, GetIvar([self class], "_age")) intValue];
}

// Person 类 age 属性的 setter
void setAge(id self, SEL _cmd, int age) {
    return object_setIvar(self, GetIvar([self class], "_age"), @(age));
}

用 Runtime 动态创建一个 Person 类

void allocatePersonClass() {
    // 创建 Person 类
    Class class = objc_allocateClassPair([NSObject class], "Person", 0);

    // 为 name 属性添加成员变量
    class_addIvar(class, "_name", sizeof(NSString*), 1, @encode(NSString));
    // 为 age 属性添加成员变量
    class_addIvar(class, "_age", sizeof(int), 2, @encode(int));

    // 为 name 属性添加 getter、setter
    class_addMethod(class, sel_registerName("name"), (IMP)name, "@16@0:8");
    class_addMethod(class, sel_registerName("setName:"), (IMP)setName, "v24@0:8@16");

    // 为 age 属性添加 getter、setter
    class_addMethod(class, sel_registerName("age"), (IMP)age, "i16@0:8");
    class_addMethod(class, sel_registerName("setAge:"), (IMP)setAge, "v20@0:8i16");
    
    // 为 Person 类添加 name 属性
    objc_property_attribute_t nameAttrs[] = {
        {"T", "@\"NSString\""}, // 类型:NSString
        {"N", ""},              // 原子性:nonatomic
        {"C", ""},              // 内存管理:copy
        {"V", "_name"}          // 变量名:_name
    };
    class_addProperty(class, "name", nameAttrs, 4);

    // 为 Person 类添加 age 属性
    const objc_property_attribute_t ageAttrs[] = {
        {"T", "i"},             // 类型:int
        {"N", ""},              // 原子性:nonatomic
        {"V", "_age"}           // 变量名:_age
    }; // 内存管理:默认 assign
    class_addProperty(class, "age", ageAttrs, 3);

    // 为 Person 类添加一个 sayHello 方法
    class_addMethod(class, sel_registerName("sayHello"), (IMP)sayHello, "v16@0:8");

    // 通过 Block 的方式为 Person 类添加一个 run 方法
    class_addMethod(class, sel_registerName("run"), imp_implementationWithBlock(^(id self, SEL _cmd) {
        NSLog(@"我跑啊跑啊跑啊跑。。。");
    }), "v16@0:8");

    // 注册 Person 类
    objc_registerClassPair(class);
}

用 Runtime 动态创建一个 Singer 协议

void allocateSingerProtocol() {
    // 创建 Singer
    Protocol *protocol = objc_allocateProtocol("Singer");
    // 为 Singer 协议添加一个 sing 实例方法
    protocol_addMethodDescription(protocol, sel_registerName("sing"), "v16@0:8", YES, YES);
    // 注册 Singer 协议
    objc_registerProtocol(protocol);
}

用 Runtime 动态创建一个 Star 类

void allocateStarClass() {
    // 创建 Star 类,继承自 Person 类
    Class class = objc_allocateClassPair(objc_getClass("Person"), "Star", 0);
    // 为 Star 类添加 Singer 协议
    class_addProtocol(class, objc_getProtocol("Singer"));

    // 为 Star 类添加一个 _company 成员变量
    class_addIvar(class, "_company", sizeof(NSString*), 3, @encode(NSString));

    // 为 Start 类实现 Singer 协议中的 sing 方法
    class_addMethod(class, sel_registerName("sing"), imp_implementationWithBlock(^(id self, SEL _cmd) {
        NSLog(@"la la la so mi ~");
    }), "v16@0:8");

    // 注册 Star 类
    objc_registerClassPair(class);
}

用 Runtime API 查看 Person 类的结构

  • 查看成员变量:

    void lookIvars(Class class) {
        unsigned count;
        Ivar *ivars = class_copyIvarList(class, &count); // 成员变量列表
    
        for (int i = 0; i < count; i++) {
            Ivar ivar = ivars[i]; // 成员变量
            const char *name = ivar_getName(ivar); // 变量名
            const char *typeEncoding = ivar_getTypeEncoding(ivar); // 类型编码
            ptrdiff_t offset = ivar_getOffset(ivar); // 偏移量
            printf("%s %s %zd\n", name, typeEncoding, offset);
        }
    
        free(ivars);
    }
    
  • 查看属性:

    void lookProperties(Class class) {
        unsigned int count;
        objc_property_t *properties = class_copyPropertyList(class, &count); // 属性列表
    
        for (int i = 0; i < count; i++) {
            objc_property_t property = properties[i]; // 属性
            const char *name = property_getName(property); // 属性名
            const char *attrs_desc = property_getAttributes(property); // 属性描述
            printf("%s %s\n", name, attrs_desc);
    
            unsigned attrsCount;
            objc_property_attribute_t *attrs = property_copyAttributeList(property, &attrsCount); // 描述属性的属性列表
    
            for (int j = 0; j < attrsCount; j++) {
                objc_property_attribute_t attr = attrs[j]; // 描述属性的属性
                printf("%s %s\n", attr.name, attr.value); // name:名称,value:值
            }
    
            printf("\n");
        }
    
        free(properties);
    }
    
  • 查看方法:

    void lookMethods(Class class) {
        unsigned int count;
        Method *methods = class_copyMethodList(class, &count); // 方法列表
    
        for (int i = 0; i < count; i++) {
            Method method = methods[i]; // 方法
            const char *name = sel_getName(method_getName(method)); // 方法名
            const char *typeEncoding = method_getTypeEncoding(method); // 类型编码
            printf("%s %s\n", name, typeEncoding);
        }
    
        free(methods);
    }
    
allocatePersonClass();
Class class = objc_getClass("Person");

printf("\n---- 变量 ----\n");
lookIvars(class);

printf("\n---- 属性 ----\n");
lookProperties(class);

printf("\n---- 方法 ----\n");
lookMethods(class);

通过打印结果可以看到动态创建的类结构正常。


使用 Star 创建对象,并访问属性、成员变量、方法

allocatePersonClass();
allocateSingerProtocol();
allocateStarClass();

Class class = objc_getClass("Star");
id star = [[class alloc] init];

[star setValue:@"锅盖" forKey:@"name"];
NSString *name = [star valueForKey:@"name"];

[star setValue:@22 forKey:@"age"];
int age = [[star valueForKey:@"age"] intValue];

object_setIvar(star, GetIvar(class, "_company"), @22);
NSString *company = object_getIvar(star, GetIvar(class, "_company"));

NSLog(@"Star:%@, %d, %@", name, age, company);

[star performSelector:NSSelectorFromString(@"sayHello")];
[star performSelector:NSSelectorFromString(@"run")];
[star performSelector:NSSelectorFromString(@"sing")];

通过打印结果可以看到 Star 可以正常使用。


交换方法实现

需求是为所有 ViewController 的生命周期方法进行埋点,可以通过 Runtime 已少量的代码实现,并且不需要在每个 ViewController 的生命周期方法中增加代码。

@interface UIViewController (Hook)

@end

@implementation UIViewController (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^ {
        // hook:钩子函数
        Method method1 = class_getInstanceMethod(self, @selector(viewDidLoad));
        Method method2 = class_getInstanceMethod(self, @selector(hook_viewDidLoad));
        method_exchangeImplementations(method1, method2);
    });
}

- (void)hook_viewDidLoad {
    // do someting...
    [self hook_viewDidLoad];
}

@end

objc_property_attribute_t

用来描述一个属性的类型、读写性、内存管理、原子性、变量名。

typedef struct {
     const char * _Nonnull name;
     const char * _Nonnull value;
 } objc_property_attribute_t;
  • 类型:

    • name:T
    • value:
      • 基本数据类型:i - int,f - float,d - double,q - NSInteger,Q - NSUInteger
      • id:@
      • 对象类型:@"ClassName",例如 @"NSString"
      • Block:@?
  • 读写性:

    • name:readwrite - 无(默认),readonly - R
    • value:""
  • 内存管理:

    • name:assign - 无(基本数据类型时为默认),strong - &(对象类型时为默认),weak - W,copy - C
    • value:""
  • 原子性:

    • name:atomic - 无(默认),nonatomic - N
    • value:""
  • 变量名:

    • name:V
    • value:变量名

使用 property_getAttributes() 函数获取的是一个属性所有 objc_property_attribute_t 的字符串拼接:

  • 类型、读写性、内存管理、原子性、变量名。
  • (attr1.name + attr1.value), (attr2.name + attr2.value)

相关文章

  • Runtime 04 - 应用(动态创建类、交换方法)

    Runtime 04 - 应用(动态创建类、交换方法) 动态创建类 需要创建的类结构如下 动态创建类的示例 先定义...

  • runtime的理解(二)

    主要内容 利用 runtime 交换方法 利用 runtime 动态添加方法 利用 runtime 动态添加属性 ...

  • runtime

    runtime交换方法 动态添加方法

  • RunTime实现

    1:RunTiem交换方法实现 //runTime交换方法实现 // 1,创建已有类的分类,并且实现自己的方...

  • ios runtime

    什么是runtime runtime运用 在程序运行过程中,动态的创建类,动态添加、修改这个类的属性和方法 遍历一...

  • iOS开发经验(14)-runtime

    目录 回顾类&对象&方法 OC的动态特性 Runtime详解 应用场景 Runtime缺点及Runtime常用函数...

  • Runtime积累

    一、Runtime 可以做的是事情1、实现多继承2、交换两个方法的实现3、关联对象4、动态创建方法和类5、将 Js...

  • runtime和oc内存区域(2018-04-02)

    runtime常用的几个方法: 交换方法 动态添加属性 动态添加方法 1.交换方法 class_getClassM...

  • 【iOS篇】Runtime的应用

    我们可以运用runtime机制做一些事情,动态的获取类的一些属性和方法,动态添加方法和方法交换。 1、获取类名 动...

  • 自己实现OC的KVO

    Runtime系列文章在这:Runtime介绍---术语介绍Runtime应用--动态添加方法Runtime应用-...

网友评论

      本文标题:Runtime 04 - 应用(动态创建类、交换方法)

      本文链接:https://www.haomeiwen.com/subject/hsmlsctx.html