iOS-MethodSwizzling

1,132 阅读5分钟

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

调用之后结果如下:

我们先调用的是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,从而达到交换方法的目的。