iOS-MethodSwizzling

Method Swizzling相关概念

Method SwizzlingObjective-C的黑魔法,利用runtime实现。用作方法交换,顾名思义,就是将两个方法的实现交换。比如,methodA的实现是impAmethodB的实现是impB,交换之后就是调用methodA响应的是impB,调用methodB响应的是impA

Method Swizzing是发生在运行时的。因为每个类都维护一个方法列表methodmethod中包含方法编号SEL和其实现IMP,方法交换就是把原来SELIMP的对应关系断开,并和新的IMP生成对应关系。

Method Swizzling API

method_exchangeImplementations(Method _Nonnull m1, Method _Nonnull m2) 

Method SwizzlingAPI非常简单,只需要传入两个需要交换的Method,其源码实现如下:

void method_exchangeImplementations(Method m1, Method m2)
{
    if (!m1  ||  !m2) return;

    mutex_locker_t lock(runtimeLock);
    
    // 交换IMP
    IMP m1_imp = m1->imp;
    m1->imp = m2->imp;
    m2->imp = m1_imp;

    // 更新方法的缓存
    flushCaches(nil);
    
    // 当method改变了其IMP,更新自定义的RR标志位、AWZ标志位
    // RR指retain/release  AWZ指allocWithZone
    updateCustomRR_AWZ(nil, m1);
    updateCustomRR_AWZ(nil, m2);
}

Method Swizzling的用法

了解了Method Swizzling的概念和API之后,我们来看看它是怎么使用的。

创建一个TPerson类:

@interface TPerson : NSObject

- (void)eat;
- (void)drink;

@end

#import "TPerson.h"
#import <objc/runtime.h>


@implementation TPerson

+ (void)load {
    Method oriMethod = class_getInstanceMethod([self class], @selector(eat));
    Method swiMethod = class_getInstanceMethod([self class], @selector(drink));
    method_exchangeImplementations(oriMethod, swiMethod);
}

- (void)eat {
    NSLog(@"====eat====");
}

- (void)drink {
    NSLog(@"====drink====");
}

@end

调用之后结果如下:

image

我们先调用的是eat方法,因为经过了交换,所以先响应了drink

Method Swizzling的注意点

1. 类簇的相关使用

@interface NSArray (addition)

@end

#import "NSArray+addition.h"
#import <objc/runtime.h>

@implementation NSArray (addition)

+ (void)load{
    Method oriMethod = class_getInstanceMethod([self class], @selector(objectAtIndex:));
    Method swiMethod = class_getInstanceMethod([self class], @selector(customObjectAtIndex:));
    method_exchangeImplementations(oriMethod, swiMethod);
}

// 自定义的交换方法
- (id)customObjectAtIndex:(NSUInteger)index{
    if (index > self.count-1) {
        NSLog(@"--customObjectAtIndex-- 数组越界 --");
        return nil;
    }
    return [self customObjectAtIndex:index];
}

@end

_dataArray = @[@"AAA", @"BBB", @"CCC", @"DDD"];
NSLog(@"--objectAtIndex--第5个元素--%@--",[_dataArray objectAtIndex:4]);

运行上述代码,会发现程序会崩溃,控制台输出数组越界:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** __boundsFail: index 4 beyond bounds [0 .. 3]'

而我们自定义的交换方法没有打印,说明方法并没有执行,即交换方法失败了。那么问题出在哪里了呢?NSArray是个类簇,其方法是在__NSArrayI这个类中,我们使用NSArray交换自然不会成功,将上述load方法中的[self class]改成objc_getClass("__NSArrayI"),然后继续运行程序,程序运行正常,控制台输出:

2020-02-21 14:59:32.359366+0800 005---Runtime应用[52032:1924598] --customObjectAtIndex-- 数组越界 --
2020-02-21 14:59:32.359565+0800 005---Runtime应用[52032:1924598] --objectAtIndex--第5个元素--(null)--

说明交换方法成功了。那么输出以下内容,会发生什么呢?

NSLog(@"--字面量--第5个元素--%@--", _dataArray[4]);

运行程序,程序崩溃,控制台输出:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndexedSubscript:]: index 4 beyond bounds [0 .. 3]'

原来字面量取值赋值使用的是objectAtIndexedSubscript,那我们需要交换的是__NSArrayIobjectAtIndexedSubscript方法,给load方法添加如下代码:

Method oriMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndexedSubscript:));
Method swiMethod = class_getInstanceMethod([self class], @selector(customObjectAtIndexedSubscript:));
method_exchangeImplementations(oriMethod, swiMethod);

并实现customObjectAtIndexedSubscript方法:

- (id)customObjectAtIndexedSubscript:(NSUInteger)index{
    if (index > self.count-1) {
        NSLog(@"--customObjectAtIndexedSubscript-- 字面量数组越界 --");
        return nil;
    }
    return [self customObjectAtIndexedSubscript:index];
}

运行程序,控制台输出:

2020-02-21 15:09:48.163626+0800 005---Runtime应用[52139:1930192] --customObjectAtIndexedSubscript-- 字面量数组越界 --
2020-02-21 15:09:48.163754+0800 005---Runtime应用[52139:1930192] --字面量--第5个元素--(null)--

上述例子有一个需要改进的地方,如果再有外界调用NSArrayload方法,就会把方法换回来,所以我们只需要让交换的方法执行一次。可以将交换的方法写成单例弥补这一缺陷。

交换NSArray、NSMutableArray、NSDictionary、NSMutableDictionary的时候注意类簇的问题:

  • NSArray -> __NSArrayI
  • NSMutableArray -> __NSArrayM
  • NSDictionary -> __NSDictionaryI
  • NSMutableDictionary -> __NSDictionaryM

2. 父类和子类方法的互相交换

@interface TPerson : NSObject

- (void)eat;

@end

@implementation TPerson

- (void)eat {
    NSLog(@"==TPerson==eat====");
}

@end


@interface TStudent : TPerson

@end

@implementation TStudent

+ (void)load {
    Method oriMethod = class_getInstanceMethod([self class], @selector(study));
    Method swiMethod = class_getInstanceMethod([self class], @selector(eat));
    method_exchangeImplementations(oriMethod, swiMethod);
}

- (void)study {
    [self study];
}

@end

当我们调用以下方法的时候,就会崩溃:

    TStudent *stu = [[TStudent alloc] init];
    [stu eat];
    
    TPerson *person = [[TPerson alloc] init];
    [person eat];
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TPerson study]: unrecognized selector sent to instance 0x6000035905e0'

因为TPersoneat方法已经和TStudentstudy方法进行了交换,当我们执行[stu eat]的时候,执行的是TPersoneat方法,然而执行[person eat]的时候,其IMP的实现已经变成了study,而TPerson没有study方法,所以就会崩溃。

解决方法:交换之前先给该类添加一下需要交换的方法,如果能够添加成功,就说明该类没有这个方法的实现,可以直接替换原来的方法,如果添加失败说明该类有了这个方法的实现了,父类调用的时候也不会崩溃了,就直接交换即可。

实现如下:

Method oriMethod = class_getInstanceMethod(cls, oriSEL);
Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);
   
// 尝试添加
BOOL success = class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(oriMethod));

if (success) {// 自己没有 - 交换 - 没有父类进行处理 (重写一个)
    class_replaceMethod(cls, swizzledSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
}else{ // 自己有
    method_exchangeImplementations(oriMethod, swiMethod);
}

3. 父类和子类都没有实现

如果该类原来的方法都没有实现,那么上述例子的处理还是有问题,因为没有的实现的时候就会出现循环调用。我们可以在原方法也没有实现了的时候给其添加一个空的实现,这就防止了循环调用。

Method oriMethod = class_getInstanceMethod(cls, oriSEL);
Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);
    
if (!oriMethod) {
    // 在oriMethod为nil时,替换后将swizzledSEL复制一个不做任何事的空实现,代码如下:
    class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
        
    method_setImplementation(swiMethod, imp_implementationWithBlock(^(id self, SEL _cmd){ }));
}
    
// 一般交换方法: 交换自己有的方法 -- 走下面 因为自己有意味添加方法失败
// 交换自己没有实现的方法:
// 首先第一步:会先尝试给自己添加要交换的方法 
// 然后再将父类的IMP给swizzle 

BOOL didAddMethod = class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
if (didAddMethod) {
    class_replaceMethod(cls, swizzledSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
}else{
    method_exchangeImplementations(oriMethod, swiMethod);
}

总结:

Method SwizzlingObjective-C动态性的最好体现,其主要的点就在于交换两个MethodIMP,从而达到交换方法的目的。

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

推荐阅读更多精彩内容