Runtime的应用

2017-09-10  本文已影响10人  sunny_王

来自:http://www.imlifengfeng.com/blog/?p=397
runtime是运行时库(Runtime Library),也简称运行时。
它是一个主要是C和汇编写的库,对C进行了特殊的处理,将结构体视为对象,将函数视为方法,使得C有了面向对象的能力,从而才创造了Objective-C。
这点也可以看出,C是编译时语言,而OC是动态运行时语言,所以在编译阶段,尽管OC中的方法没有实现也不会报错,而C会报错。
在运行时,OC语言才进行方法的处理,比如讲[person eat];转换为objc_msgSend(person, @selector(eat));然后通过person的isa指针找到person对应的class,在class中先去cache中通过SEL方法选择器查找对应的method,若缓存中未找到,再去methodList查找,若还未找到,便去父类中查找,如果这个过程中找到了该方法,便会自动将该方法加入cache中,方便下一次的查找,并且,编译器开始执行找到的这个函数。
1、快速归档

2、Json到Model的转化

3、Category添加属性并生成getter和setter方法

import <Foundation/Foundation.h>

@interface NSArray (MyCategory)
//不会生成添加属性的getter和setter方法,必须我们手动生成
@property (nonatomic, copy) NSString *blog;
@end

import "NSArray+MyCategory.h"

import <objc/runtime.h>

@implementation NSArray (MyCategory)

// 定义关联的key
static const char *key = "blog";

/**
blog的getter方法
*/

/**
blog的setter方法
*/

4、Method Swizzling使用

import "UIViewController+swizzling.h"

import <objc/runtime.h>

@implementation UIViewController (swizzling)

// 我们自己实现的方法,也就是和self的viewDidLoad方法进行交换的方法。

5、Method Swizzling类簇
__NSArrayI才是NSArray真正的类

import "NSArray+ MyArray.h"

import "objc/runtime.h"

@implementation NSArray MyArray)

6、runtime添加类方法
[objc] view plain copy
void study(id reccevier, SEL sel) {
}
// 如果调用的方法没有实现,就会走这个方法

上一篇 下一篇

猜你喜欢

热点阅读