//
// 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;
}
object c runtime的学习
最新推荐文章于 2020-07-09 15:01:51 发布