object c runtime的学习

//
//  main.m
//  RuntimeFunctionApplication
//
//  Created by 千雅爸爸 on 16/10/7.
//  Copyright © 2016年 kodulf. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import "Person.h"
#import <objc/message.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //runtime的了解
        //runtime 是一套由c语言api组合成的runtime库,
        //runtime 会尽可能把代码的执行决策推迟到运行时
        //oc 是动态语言,oc代码最终都会转换成底层runtime的代码
        //[person setAge:10]
        //objc_msgSend(person,@selector(setAge:),10);
        
        //runtime的使用
        //动态获取/创建类
        //动态为一个类增加属性或方法
        //在程序运行时便利类中的实例变量,属性或方法
        //调换两个方法的逻辑实现(method swizzle)
        
        //比如说我们要统计用户的点击时间或者是用户的访问率
        
        //首先引入runtime的头文件,#import <objc/runtime.h>
        //创建一个类person,
        
        Person *person = [Person person];
        NSLog(@"%@",[person class]);
        
        //如何去利用runtime去动态的获取类中的实例变量:
        Class personClass = person.class;
        unsigned int outCount = 0;
        //遍历实例变量
        Ivar *ivarPtr =class_copyIvarList(personClass, &outCount);//新类型的指针变量
        for (NSInteger i=0;i<outCount;i++) {
            Ivar ivar = ivarPtr[i];
            NSLog(@"实例变量:%s",ivar_getName(ivar));//获取实例变量,
        }
        //遍历类中的属性
        objc_property_t *propertyPtr = class_copyPropertyList(personClass, &outCount);
        for (NSInteger i=0; i<outCount; i++) {
            objc_property_t property = propertyPtr[i];
            NSLog(@"类的属性:%s",property_getName(property));
        }
        
        //遍历对象方法:
        Method *methodPtr = class_copyMethodList(personClass, &outCount);
        for (NSInteger i=0; i<outCount; i++) {
            Method method = methodPtr[i];
            SEL selector = method_getName(method);
            NSLog(@"对象方法:%@",NSStringFromSelector(selector));
        }
        
        //oc消息发送时候的隐藏实现函数
        //首先导入#import <objc/message.h>
        //点击左侧里里面的文件夹标志下面的第一个项目名的蓝色图标,中间好像又一个a的字,找到buildsetting,搜索框输入objc,在preprocessing 里面
        //将enable strict checking of objc_msgSend Calls 设置为no
        //相当于告诉我们的编译器,不要去检查我们对雨objc_msgSend的方法的调用
        
        [person setAge:10];//这个是oc的消息的发送。
        NSLog(@"%@",person);
        //下面的和上面实现相同的功能,只是下面的是上面的底层实现而已
        objc_msgSend(person,@selector(setAge:),15);//如果没有将enable strict checking of objc_msgSend Calls 设置为no,那么会报错,说是需要0个参数,但是现在有3个参数
        NSLog(@"%@",person);
    }
    return 0;
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值