通过runtime修改系统默认的字体、颜色等等

6.jpg

这个是我写的一个demo,你们可以去看看,欢迎star
https://github.com/mafangchao/MCChangeLabelFont-OC/tree/master
一、关于runtime

之前在项目中有遇到过用runtime解决改变全局字体的问题,所以再一次感受到了runtime黑魔法的强大,趁现在有机会分享一下对runtime的一些理解。在对象调用方法是Objective-C中经常使用的功能,也就是消息的传递,而Objective-C是C的超集,所以和C不同的是,Objective-C使用的是动态绑定,也就是runtime。Objective-C的消息传递和消息机制也就不多说了,今天主要说的是动态方法,也就是函数的调用。

二、相关的几个函数

消息传递函数的调用

1.对象在收到无法解读的消息后,首先会调用所属类的

  • (BOOL)resolveInstanceMethod:(SEL)sel
    这个方法在运行时,没有找到SEL的IML时就会执行。这个函数是给类利用class_addMethod添加函数的机会。根据文档,如果实现了添加函数代码则返回YES,未实现返回NO。举个例子,新建了一个工程,首先我在ViewController这个类中执行doSomething1这个方法,代码如下

import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(doSomething)];
    }

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

@end
运行结果

2015-12-24 10:35:37.726 RuntimeTest1[1877:337842] -[ViewController doSomething]: unrecognized selector sent to instance 0x7fe9f3736680
2015-12-24 10:35:37.729 RuntimeTest1[1877:337842] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7fe9f3736680'
***** First throw call stack:**
不出意外,程序崩溃,因为没有找到doSomething这个方法,下面我们在里面实现 + (BOOL)resolveInstanceMethod:(SEL)sel这个方法,并且判断如果SEL 是doSomething那就输出add method here

import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(doSomething)];
    }
  • (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(doSomething)) {
    NSLog(@"add method here");
    return YES;
    }
    return [super resolveInstanceMethod:sel];
    }
  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

@end
继续运行,然后看到log

2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] add method here
2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] -[ViewController doSomething]: unrecognized selector sent to instance 0x7f9568c331f0
2015-12-24 10:47:24.690 RuntimeTest1[2007:382077] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7f9568c331f0'
***** First throw call stack:**
可以看到程序依然是崩溃了,但是我们可以看到输出了add method here,这说明我们 + (BOOL)resolveInstanceMethod:(SEL)sel这个方法执行了,并进入了判断,所以,在这儿,我们可以做一下操作,使这个方法得到相应,不至于走到最后- (void)doesNotRecognizeSelector:(SEL)aSelector这个方法中而崩掉了,接下来,我么继续操作,如下

import "ViewController.h"

import objc/runtime.h

@interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(doSomething)];
    }
  • (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(doSomething)) {
    NSLog(@"add method here");
    class_addMethod([self class], sel, (IMP)dynamicMethodIMP, "v@:");
    return YES;
    }
    return [super resolveInstanceMethod:sel];
    }
    void dynamicMethodIMP (id self, SEL _cmd) {
    NSLog(@"doSomething SEL");
    }
  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

@end
导入了并且在+ (BOOL)resolveInstanceMethod:(SEL)sel中执行了class_addMethod这个方法,然后定义了一个void dynamicMethodIMP (id self, SEL _cmd)这个函数,运行工程,看log

2015-12-24 11:45:11.934 RuntimeTest1[2284:478571] add method here
2015-12-24 11:45:11.934 RuntimeTest1[2284:478571] doSomething SEL
这时候我们发现,程序并没有崩溃,而且还输出了doSomething SEL,这时候就说明我们已经通过runtime成功的向我们这个类中添加了一个方法。关于class_addMethod这个方法,是这样定义的

OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
cls 在这个类中添加方法,也就是方法所添加的类
name 方法名,这个可以随便起的
imp 实现这个方法的函数
types 定义该数返回值类型和参数类型的字符串,这里比如"v@:",其中v就是void,带表返回类型就是空,@代表参数,这里指的是id(self),这里:指的是方法SEL(_cmd),比如我再定义一个函数

int newMethod (id self, SEL _cmd, NSString *str) {

return 100;
}
那么添加这个函数的方法就应该是ass_addMethod([self class], @selector(newMethod), (IMP)newMethod, "i@:@");

2.如果在+ (BOOL)resolveInstanceMethod:(SEL)sel中没有找到或者添加方法

消息继续往下传递到- (id)forwardingTargetForSelector:(SEL)aSelector看看是不是有对象可以执行这个方法,我们来重新建个工程,然后新建一个叫SecondViewController的类,里面有一个- (void)secondVCMethod方法,如下

import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    }

  • (void)secondVCMethod {
    NSLog(@"This is secondVC method !");
    }

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

/*

pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */

@end

现在我想在ViewController中调用- (void)secondVCMethod这个方法,我们知道ViewController和SecondViewController并无继承关系,按照正常的步骤去做程序肯定会因为在ViewController找不到- (void)secondVCMethod这个方法而直接崩溃的

import "ViewController.h"

import @interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(secondVCMethod)];
    }

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

@end
运行结果

2015-12-24 13:54:44.314 RuntimeTest2[3164:835814] -[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fc3a8535c10
2015-12-24 13:54:44.317 RuntimeTest2[3164:835814] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fc3a8535c10'
***** First throw call stack:**
现在我们来处理一下这个消息,如下

import "ViewController.h"

import @interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(secondVCMethod)];
    }

  • (id)forwardingTargetForSelector:(SEL)aSelector {
    Class class = NSClassFromString(@"SecondViewController");
    UIViewController *vc = class.new;
    if (aSelector == NSSelectorFromString(@"secondVCMethod")) {
    NSLog(@"secondVC do this !");
    return vc;
    }

    return nil;
    }

  • (BOOL)resolveInstanceMethod:(SEL)sel {

    return [super resolveInstanceMethod:sel];
    }

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }
    @end
    运行结果
    2015-12-24 14:00:34.168 RuntimeTest2[3284:870957] secondVC do this !
    2015-12-24 14:00:34.169 RuntimeTest2[3284:870957] This is secondVC method !
    我们会发现- (void)secondVCMethod这个方法执行了,程序也并没有崩溃,原因就是在这一步

  • (id)forwardingTargetForSelector:(SEL)aSelector {
    Class class = NSClassFromString(@"SecondViewController");
    UIViewController *vc = class.new;
    if (aSelector == NSSelectorFromString(@"secondVCMethod")) {
    NSLog(@"secondVC do this !");
    return vc;
    }

    return nil;
    }
    在没有找到- (void)secondVCMethod这个方法的时候,消息继续传递,直到- (id)forwardingTargetForSelector:(SEL)aSelector,然后我在里面创建了一个SecondViewController的对象,并且判断如过有这个方法,就返回SecondViewController的对象。这个函数就是消息的转发,在这儿我们成功的把消息传给了SecondViewController,然后让它来执行,所以就执行了那个方法。同时,也相当于完成了一个多继承!

三、最后一点

当然,还有好几个函数,在上面那张图里面已经清晰的表达了,有兴趣的可以自己试试,看看消息的传递顺序到底是怎么样的。上面提到的这些知识runtime的冰山一角,runtime黑魔法的强大远不止于此,比如方法的调配(Method Swizzling)等,在项目实战中还是很有用的,后面有时间会再介绍.

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

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,635评论 0 9
  • 一、关于runtime 之前在项目中有遇到过用runtime解决改变全局字体的问题,所以再一次感受到了runtim...
    沐暮风阅读 669评论 0 51
  • 一、关于runtime 之前在项目中有遇到过用runtime解决改变全局字体的问题,所以再一次感受到了runtim...
    Eric_zheng阅读 293评论 0 0
  • 我们常常会听说 Objective-C 是一门动态语言,那么这个「动态」表现在哪呢?我想最主要的表现就是 Obje...
    Ethan_Struggle阅读 2,109评论 0 7
  • 【解剖列车】笔记的整理来自李哲老师。老师更多的是解读本书,我则是还原老师的课堂口述。 ☞本节看点——快速查看关键点...
    舒涵vivian阅读 3,453评论 0 17