Ios 运行时机制

  1. 相关头文件

    #import <objc/runtime.h>

        //获取cls中所有成员变量

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

        //获取cls类中所有方法

        class_copyMethodList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)

        //获取类方法 +号开头

        class_getClassMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>)

        //获取实例发放 -号开头

        class_getInstanceMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>)

        method_exchangeImplementations(<#Method m1#>, <#Method m2#>)



    #import <objc/message.h>

    objc_msgSend(<#id self#>, <#SEL op, ...#>)


  2. 功能
    2.1 交换两个方法的实现 (要注意是调用实例方法还是类方法)
       Method method1 =class_getInstanceMethod([Studentclass],@selector(run));
       Method method2 = class_getInstanceMethod([Studentclass], @selector(study));
        method_exchangeImplementations(method1, method2);
       Student *student = [[Studentalloc] init];
        [studentrun];
        [studentstudy];


    2.2 Ios消息方法调用,消息机制

     

    Student *stu = [[Studentalloc] init];
        //注意:若报Too many arguments to function call, expected 0, have 3错误,targets->build Setting,搜索msg设置为NO;
    
       objc_msgSend(stu,@selector(setAge:),20);
        
       NSLog(@"%d",stu.age);

    2.3 遍历类中所有成员变量

    //遍历类中所有成员变量
       
    -(void)getIvarList{
       unsigned int count=0;
       Ivar *ivars =  class_copyIvarList([Studentclass], &count);
       NSLog(@"%d---%p",count,ivars);
       for (int i=0; i<count; i++) {
           Ivar ivar = ivars[i];
           const char *name =ivar_getName(ivar); //变量名称
           const char *type =ivar_getTypeEncoding(ivar);//变量类型
           NSLog(@"%d - %s - %s",i,name,type);
        }
    }



    打印结果:

    2016-04-19 17:38:30.095 001-RunTime[1732:60419] 0 - _age - i

    2016-04-19 17:38:30.095 001-RunTime[1732:60419] 1 - _name - @"NSString"

    2016-04-19 17:38:30.095 001-RunTime[1732:60419] 2 - _score - d





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值