[iOS]Objective-C Runtime学习笔记之:注册类,为类添加成员变量、方法

1.导入工作

#import 
#import 

2.定义runtime函数

1.动态创建一个类,objc_allocateClassPair函数:第一个参数是父类。第三个参数extraBytes通常指定为0,该参数是分配给类和元类对象尾部的索引ivars的字节数。

    Class People = objc_allocateClassPair([NSObject class], "Person", 0);

2.添加成员变量,第三个参数,如果变量的类型是指针类型,则传递log2(sizeof(pointer_type))。

class_addIvar(People, "_name", sizeof(NSString *), log2(sizeof(NSString *)), @encode(NSString *));
class_addIvar(People, "_age", sizeof(int), sizeof(int), @encode(int));

3.添加方法

//最后一个参数为"v@:@“, v:返回void, i:int ,f:double, c:unsigned char等等
 SEL sel = sel_registerName("method:");
 class_addMethod(People, sel, (IMP)introduction, "v@:@");

4.定义introduction 方法

// class_getInstanceVariable获取制定名称的私有变量,kvc取值
void introduction(id self, SEL _cmd, id some) {
   NSLog(@"%@,my name is:%@,I'm %@ years old",some,[self valueForKey:@"name"],object_getIvar(self, class_getInstanceVariable([self class], "_age")));
  }

5.注册类

 objc_registerClassPair(People);

6.创建实例

 id peopleInstance = [[People alloc]init];

7.KVC 改变peopleInstance里的实例变量

 [peopleInstance setValue:@"Carrot" forKey:@"name"];

8.用object_setIvar为成员变量赋值

    //从类中获取到成员变量IVar
    Ivar age = class_getInstanceVariable(People, "_age");
    
    //为peopleInstance的成员变量赋值
    object_setIvar(peopleInstance, age, @22);

9.调用peopleInstance中的sel的方法

#warning objc_msgSend(peopleInstance, s, @"大家好!");参数过多报错 解决:Build Setting–> Apple LLVM 7.0 – Preprocessing–> Enable Strict Checking of objc_msgSend Calls 改为 NO
    
    ((void (*)(id, SEL, id))objc_msgSend)(peopleInstance, sel, @"大家好");

10.销毁

 peopleInstance = nil;
 objc_disposeClassPair(People);

你可能感兴趣的:([iOS]Objective-C Runtime学习笔记之:注册类,为类添加成员变量、方法)