对于C语言 函数的调用在编译的时候会去决定调用哪个函数
对于OC 属于动态调用过程,在编译的时候并不能决定真正调用哪个函数,只有在真正运行的时候才会根据函数名称找到对应的函数
1.发送消息
需要导入头文件<objc/massage.h> 在ios5 以后 苹果不建议开发者直接调用运行时进行开发需要手动打开运行时开发权限



2.利用运行时获得对象内部的属性和方法
<objc/runtime.h>
在runtime中 针对class 除了拿到当前class 所有的方法以外,还有

而利用runtime 拿到类所有的属性,相当于去遍历实例对象的类对象,从类对象中可以轻易得到定义的所有的属性

同理可以遍历该对象内所有的方法



值得一提的是 并没有返回该对象的类方法,也就是说runtime 的 class_copy xxxx系列方法 访问的是该类的类对象内的方法和属性列表,而类方法存放于类对象的元类中
3.Method
Method 是runtime中 用来索引方法的结构体


其中重要的是
SEL : 类成员方法的指针,但不同于C语言中的函数指针,函数指针直接保存了方法的地址,但SEL只是方法编号。
IMP:一个函数指针,保存了方法的地址
所以用来构建Method
--1.构建类方法Method
Method classFunc = class_getClassMethod(Classcls,@selector(classFunc));
--2.构建实例方法Method
Method func =class_getInstanceMethod(Classcls,@selector(run));
4.Method swizzling
传说中的ios魔法方法
核心代码其实只有一行

传进去的都是Method结构体

而在调用时结果如下

网友评论