runtime理解

1.给类动态添加方法
用的函数是 class_addMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>, <#IMP imp#>, <#const char *types#>)
Obj-C的方法(method)就是一个至少需要两个参数(self,_cmd)的C函数,
类似于

void newFunction(id self,SEL _cmp,NSString *string){

    NSLog(@"string = %@",string);

}

参数说明:

cls:被添加方法的类

name:可以理解为方法名,这个貌似随便起名,比如我们这里叫sayHello2

imp:实现这个方法的函数

types:一个定义该函数返回值类型和参数类型的字符串,这个具体会在后面讲

其中types参数为"i@:@“,按顺序分别表示:

i:返回值类型int,若是v则表示void

@:参数id(self)

::SEL(_cmd)

@:id(str)

这些表示方法都是定义好的(Type Encodings),关于Type Encodings的其他类型定义请参考官方文档

最后调用say:方法:

2:获取所有的属性包括定义在{}里面的

Ivar*vaaa=class_copyIvarList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)

参数说明:第一个是类名 第二个是该类的所有属性的总数目具体用法如下

unsigned int count = 0;

     //获取一个类当中所有的成员变量的值和类型

    Ivar *varArr=class_copyIvarList([Student class], &count);

    for (NSInteger i=0; i<count; i++) {

        Ivar var=varArr[i];

        NSString*name=[NSString stringWithCString:ivar_getName(var) encoding:NSUTF8StringEncoding];

        NSString*typ=[NSString stringWithCString:ivar_getTypeEncoding(var) encoding:NSUTF8StringEncoding];

   NSLog(@"name=%@\n type=%@\n",name,typ);

  }

    Student*student=[Student new];

    Ivar var=varArr[0];

    Ivar varId=varArr[1];

    object_setIvar(student, var, @"xiaoming");

    object_setIvar(student, varId, @"3112002956");

NSLog(@"name=%@\nID=%@\n",student.name,student.ID);

3:获取所有的方法包括属性的get方法和set方法

unsigned int count=0;

    

    Method*methodArr=class_copyMethodList([Student class], &count);

    for (NSInteger i=0; i<count; i++) {

        Method method=methodArr[i];

        //返回SEL方法选择器当中包含的方法名

        //NSStringFromSelector->反射

        SEL selector=method_getName(method);

        NSString*methodName=NSStringFromSelector(selector);

        NSLog(@"methodName%@",methodName);

        

    }

    Student*student=[Student new];

    //强制执行方法

    [studentperformSelector:@selector(loveMoney)];

4:修改某一个方法的实现

Method method =  class_getInstanceMethod([Student class], @selector(loveMoney));

    

    //修改方法的实现

    method_setImplementation(method, (IMP)function1);

    

    

    Student *student = [Student new];

    

    //强制调用

    [student performSelector:@selector(loveMoney)];

具体为什么要写这两个参数还想不明白

void function1(id self,SEL _cmp){

    NSLog(@"%s",__func__);

}










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值