Runtime 知识点

Runtime 是什么? Runtime 有什么作用?

1. Rutime 是什么?

1.1. Runtime 简称运行时,就是系统在运行的时候的一些机制,其中最主要的是消息机制.

当我们编写 OC 代码之后,当运行之后都会变成 runtime 的方式运行.比如:
OC 代码:[tableViewre loadData];
运行之后转换为
Runtime 代码:objc_msgSend(tableView, @selector(reloadData));

1.2. Rutime常用方法

创建一个 Person 类:

#import <Foundation/Foundation.h>

@interface Person : NSObject{
    /**
     成员变量
     */
    NSInteger   _age;
    NSString    *_gender;
}

/**
 属性
 */
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *identyfier;

/**
 方法
 */
- (void)eatByFood:(NSString *)food;

+ (void)run;

+ (void)walk;

@end
#import "Person.h"

@implementation Person

- (void)eatByFood:(NSString *)food {
    NSLog(@"吃%@", food);
}

+ (void)run {
    NSLog(@"跑步");
}

+ (void)walk {
    NSLog(@"走路");
}

@end
  • 获取此类的属性列表
unsigned int count;
//属性列表
objc_property_t *propertyList = class_copyPropertyList([Person class], &count);
//打印每个属性的名称
for (unsigned int i = 0; i < count; i++) {
    const char *propertyName = property_getName(propertyList[i]);
    NSLog(@"PropertyName -- %@", [NSString stringWithUTF8String:propertyName]);
}
Log:
2017-11-18 14:06:12.187593+0800 runtime[845:20588170] PropertyName -- name
2017-11-18 14:06:12.188593+0800 runtime[845:20588170] PropertyName -- identyfier
  • 获取此类的成员列表
unsigned int count;
//成员变量列表
Ivar *ivarList = class_copyIvarList([Person class], &count);
//打印每个成员变量的名称
for (unsigned int i = 0; i < count; i++) {
    const char *ivarName = ivar_getName(ivarList[i]);
    NSLog(@"IvarName -- %@", [NSString stringWithUTF8String:ivarName]);
}
Log:
2017-11-18 14:15:33.972601+0800 runtime[1232:20657314] IvarName -- _age
2017-11-18 14:15:33.972724+0800 runtime[1232:20657314] IvarName -- _gender
2017-11-18 14:15:33.972827+0800 runtime[1232:20657314] IvarName -- _name
2017-11-18 14:15:33.972919+0800 runtime[1232:20657314] IvarName -- _identyfier
  • 获取此类的方法列表
//方法列表
Method *methodList = class_copyMethodList([Person class], &count);
//打印每个方法的名称
for (unsigned int i = 0; i < count; i++) {
    Method method = methodList[i];
    SEL method_sel = method_getName(method);
    NSLog(@"MethodName -- %@", NSStringFromSelector(method_sel));
}
2017-11-18 14:38:14.811410+0800 runtime[2235:20835336] MethodName -- eatByFood:
2017-11-18 14:38:14.811519+0800 runtime[2235:20835336] MethodName -- identyfier
2017-11-18 14:38:14.812418+0800 runtime[2235:20835336] MethodName -- setIdentyfier:
2017-11-18 14:38:14.814270+0800 runtime[2235:20835336] MethodName -- .cxx_destruct
2017-11-18 14:38:14.814633+0800 runtime[2235:20835336] MethodName -- name
2017-11-18 14:38:14.814794+0800 runtime[2235:20835336] MethodName -- setName:
  • 获取此类的类方法
Method runMethod = class_getClassMethod([Person class], @selector(run));
Method walkMethod = class_getClassMethod([Person class], @selector(walk));
  • 获取此类的实例方法
Method eatMethod = class_getInstanceMethod([Person class], @selector(eatByFood:));
  • 交换方法
Method runMethod = class_getClassMethod([Person class], @selector(run));
Method walkMethod = class_getClassMethod([Person class], @selector(walk));
method_exchangeImplementations(runMethod, walkMethod);

2. Runtime 有什么作用?

  • Category 添加属性的绑定;
  • 动态添加方法(方法懒加载);
  • 交换两个方法的实现;
  • 替换系统已有的方法;
  • 消息转发机制;

2.1. Category 添加属性的绑定

添加类 Person 的分类并且添加属性绑定:

#import "Person.h"

@interface Person (Extension)

@property (nonatomic, copy) NSString *occupation;

@end
#import "Person+Extension.h"
#import <objc/message.h>

@implementation Person (Extension)

static const char *OccupationKey = "OccupationKey";

- (void)setOccupation:(NSString *)occupation {
    objc_setAssociatedObject(self, OccupationKey, occupation, OBJC_ASSOCIATION_ASSIGN);
}

- (NSString *)occupation {
    return objc_getAssociatedObject(self, OccupationKey);
}

@end

2.2. 动态添加方法

Person *p = [[Person alloc] init];
[p performSelector:@selector(study:) withObject:@(8)];

类中不存在study:方法,此时找不到此方法,因此程序执行会 Crash.
为此类动态添加 study: 方法:

/**
 当 Runtime 系统在 Cache 和类的方法列表(包括父类)中找不到要执行的方法时,
 Runtime 会调用 resolveInstanceMethod: 或 resolveClassMethod: 来给我们一次动态添加方法实现的机会。
 我们需要用 class_addMethod 函数完成向特定类添加特定方法实现的操作:
 */
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if ([NSStringFromSelector(sel) isEqualToString:@"study:"]) {
        class_addMethod(self, sel, (IMP)custom_study_method, "v@:@");
    }
    return [super resolveInstanceMethod:sel];
}

void custom_study_method(id self, SEL _cmp, id hour) {
    NSLog(@"学习了%@小时", hour);
}

2.3. 交换两个方法的实现

未交换前的调用此两个方法

[Person run];
[Person walk];
Log:
2017-11-18 16:21:57.626816+0800 runtime[6415:21623838] 跑步
2017-11-18 16:21:57.627144+0800 runtime[6415:21623838] 走路

交换方法

+ (void)load {
    Method runMethod = class_getClassMethod(self, @selector(run));
    Method walkMethod = class_getClassMethod(self, @selector(walk));
    method_exchangeImplementations(runMethod, walkMethod);
}

在交换后的调用此两个方法

[Person run];
[Person walk];
Log:
2017-11-18 16:26:51.442822+0800 runtime[6748:21682758] 走路
2017-11-18 16:26:51.443171+0800 runtime[6748:21682758] 跑步

明显看得出虽然都是调用的同样方法,但打印的结果已经调换了.

2.4. 替换已有的方法

在编码中,假设系统类中的某个方法,我们需要改变这个方法的实现.而恰恰我们又改不了系统类的源码(或者是自己写的类和第三方不想去改源码),这时候可以用 runtime 来实现.

//第一种
//url 中不包含中文
NSURL *url = [NSURL URLWithString:@"www.baidu.com"];
NSLog(@"%@", url);
Log:
2017-11-18 17:07:05.608822+0800 runtime[8349:21965250] www.baidu.com
//第二种
//url 中包含中文
NSURL *url = [NSURL URLWithString:@"www.baidu.com/百度"];
NSLog(@"%@", url);
Log:
2017-11-18 17:05:50.173236+0800 runtime[8268:21947324] (null)

第一种和第二种就只是加了中文字的区别,而打印之后的 url 却为 null.
此时,仍然使用此 URLWithString,但要区别url是否为空.并且做相应的处理.
添加类 NSURL 的分类

#import <Foundation/Foundation.h>

@interface NSURL (Extension)

@end
#import "NSURL+Extension.h"
#import <objc/message.h>

@implementation NSURL (Extension)

+ (void)load {
    Method urlMethod = class_getClassMethod([self class], @selector(URLWithString:));
    Method yxl_urlMethod = class_getClassMethod([self class], @selector(yxl_URLWithString:));
    method_exchangeImplementations(urlMethod, yxl_urlMethod);
}

+ (instancetype)yxl_URLWithString:(NSString *)URLString {
    
    NSURL *url = [self yxl_URLWithString:URLString];
    if (url == nil) {
        /**
         在这里处理操作
         */
        NSLog(@"此链接为空...");
    }
    return url;
}

@end

添加之后,运行结果就有相应的提示:

2017-11-18 17:10:11.795304+0800 runtime[8514:21993184] 此链接为空...
2017-11-18 17:10:11.797697+0800 runtime[8514:21993184] (null)
  • 未完待续,不正确的地方请大神们的指点,谢谢!
  • Demo的地址
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容

  • Runtime是什么 Runtime 又叫运行时,是一套底层的 C 语言 API,其为 iOS 内部的核心之一,我...
    SuAdrenine阅读 863评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,494评论 18 139
  • 概论:Runtime是Objective-C中底层的一套C语言API,是一个将C语言转化为面向对象语言的拓展。OC...
    lilei5阅读 1,044评论 0 29
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,678评论 6 342
  • 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的...
    西木阅读 30,521评论 33 466