runtime - 应用篇(2)

本篇将介绍:

  • Method swizzling原理
  • Method swizzling应用
  • Method swizzling类簇

本篇示例代码地址 https://github.com/SPIREJ/runtime-/tree/master

从需求开始说起:

例如:我们想要在一款iOS APP中追踪每一个视图控制器被用户呈现了几次,我们可能会想到以下几种方式:
手动添加
直接简单粗暴的在每个视图控制器的viewDidAppear:方法中添加追踪代码来实现,但这样会大量重复的样板代码,消耗时间,难以维护。

继承
继承是另一种可行方式,但是这要求所有被继承的视图控制器如UIViewControllerUITableViewControllerUINavigationController都在viewDidAppear:实现追踪代码,这同样会定制性差,造成很多重复代码。

Category
我们可以为UIViewController建一个Category,然后在所有控制器中引入这个Category。当然我们也可以添加一个PCH文件,然后将这个Category添加到PCH文件中。

我们创建一个Category来覆盖系统方法,系统会优先调用Category中的代码,然后再调用原类中的代码。

伪代码:

#import "UIViewController+EventGather.h"

@implementation UIViewController (EventGather)

- (void)viewDidLoad {
   NSLog(@"页面统计:%@", self);
}

@end

Method swizzling
可以使用苹果的“黑魔法”Method swizzlingMethod swizzling本质上就是对IMPSEL进行交换。

Method swizzling原理

在Objective-C中调用一个方法,其实是向一个对象发送消息,查找消息的唯一依据是selector的名字。利用Objective-C的动态特性,可以实现在运行时偷换selector对应的方法实现。如何实现,就是接下来要说的Objective-C的运行时最具争议的黑魔法:method swizzling

Method swizzling用于改变一个已经存在的selector的实现。这项技术使得在运行时通过改变selector在类的消息分发列表中的映射从而改变方法的调用成为可能。

通过两张图片来了解一下Method swizzling的实现原理:

交换前

交换后

method swizzling没有作用前,图一中的selector原本对应着IPM2,但是为了实现特定也无需求,我们在图二中添加了selector2IMP3,并且让selector2指向了IMP3,而selector3则指向了IMP2,这样就实现了“方法互换”。

在OC语言的runtime特性中,调用一个对象的方法就是给这个对象发送消息。是通过查找接收消息对象的方法列表,从方法列表中查找对应的SEL,这个SEL对应着一个IMP(一个IMP可以对应多个SEL),通过这个IMP找到对应的方法调用。

在每个类中都有一个Dispatch Table,这个Dispatch Table本质是将类中的SELIMP(可以理解为函数指针)进行对应。而我们的Method Swizzling就是对这个table进行了操作,让SEL对应另一个IMP

Method swizzling应用

例:如上面提到的追踪视图控制器被访问的次数统计,先给UIViewController添加一个Category,然后在Category中的+ (void)load方法中添加Method swizzling方法,我们用来替换的方法也写在这个Category中。

#import "UIViewController+Tracking.h"
#import <objc/runtime.h>

@implementation UIViewController (Tracking)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Class class = [self class];
        
        SEL originalSelector = @selector(viewWillAppear:);
        SEL swizzledSelector = @selector(sp_viewWillAppear:);
        
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        // 当交换的是类方法时,使用如下:
        // Class class = object_getClass((id)self);
        // ...
        // Method originalMethod = class_getClassMethod(class, originalSelector);
        // Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
        
        BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        }else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

- (void)sp_viewWillAppear:(BOOL)animated {
    [self sp_viewWillAppear:animated];
    NSLog(@"viewWillAppear: %@", self);
}

@end

如何使用Method swizzling

+(void)load; vs +(void)initialize;

swizzling应该只在+(void)load;中完成。在Objective-C的运行时中,每个类有两个方法都会自动调用,+(void)load;是在一个类被初始装载时调用,+(void)initialize;是在应用第一次调用该类的类方法或实例方法前调用的。两个方法都是可选的,并且只有在方法被实现的情况下才会被调用。

dispatch_once

swizzling应该只在dispatch_once中完成。由于swizzling改变了全局的状态,所以我们需要确保每个预防措施在运行时都是可用的。在dispatch_once中执行Method swizzling是一种防护措施,以保证代码块只会被执行一次并且线程安全。

Selector,Methods,& Implementations

在 Objective-C 的运行时中,selectors, methods, implementations指代了不同概念,然而我们通常会说在消息发送过程中,这三个概念是可以相互转换的。

理解selector, methods, implementation这三个概念之间关系的最好方式是:在运行时,类(Class)维护了一个消息分发列表来解决消息的正确发送。每一个消息列表的入口是一个方法(Method),这个方法映射了一对键值对,其中键值是这个方法的名字 selector(SEL),值是指向这个方法实现的函数指针 implementation(IMP)。 Method swizzling 修改了类的消息分发列表使得已经存在的 selector 映射了另一个实现 implementation,同时重命名了原生方法的实现为一个新的 selector。

调用 _cmd

下面代码在正常情况下会出现循环:

- (void)xxx_viewWillAppear:(BOOL)animated {
    [self xxx_viewWillAppear:animated];
    NSLog(@"viewWillAppear: %@", NSStringFromClass([self class]));
}

然而在交换了方法实现后就不会出现循环了。在交换了方法的实现后,xxx_viewWillAppear:方法的实现已经被替换为UIViewController -viewWillAppear:的原生实现,所以这里并不是在递归调用。

由于 xxx_viewWillAppear: 这个方法的实现已经被替换为了 viewWillAppear: 的实现,所以,当我们在这个方法中再调用 viewWillAppear: 时便会造成递归循环。

Method swizzling类簇

在项目开发过程中,经常因为NSArray数组越界或者NSDictionarykey或者value值为nil等问题导致的崩溃,对于这些问题苹果并不会报一个警告,而是直接崩溃。

由此,我们可以根据上面对Method swizzling的了解,对NSArrayNSMutableArrayNSDictionaryNSMutableDictionary等类进行Method swizzling,实现方式还是按照上面的例子来做。但是...发现Method swizzling根本不起作用,这是为什么呢?

这是因为Method swizzlingNSArray这些类簇是不起作用的,因为这些类簇类,其实是一种抽象工厂的设计模式。抽象工厂内部有很多其它继承自当前类的子类,抽象工厂会根据不同情况,创建不同的抽象对象来进行使用。例如我们调用NSArrayobjectAtIndex:方法,这个类会在方法内部判断,内部创建不同抽象类进行操作。

所以也就是我们对NSArray类进行操作其实只是对父类进行了操作,在NSArray内部会创建其他子类来执行操作,真正执行操作的并不是NSArray自身,所以我们应该对其“真身”进行操作。

下面我们实现了防止NSArray因为调用objectAtIndex:方法,取下标时数组越界导致的崩溃:

#import "NSArray+SafeArray.h"

#import <objc/runtime.h>

@implementation NSArray (SafeArray)

+ (void)load {
    [super load];
    
    Class class = objc_getClass("__NSArrayI");
    
    SEL fromSelector = @selector(objectAtIndex:);
    SEL toSelector = @selector(safe_objectAtIndex:);
    
    Method fromMethod = class_getInstanceMethod(class, fromSelector);
    Method toMethod = class_getInstanceMethod(class, toSelector);
    
    BOOL didAddMethod = class_addMethod(class, fromSelector, method_getImplementation(toMethod), method_getTypeEncoding(toMethod));
    
    if (didAddMethod) {
        class_replaceMethod(class, toSelector, method_getImplementation(fromMethod), method_getTypeEncoding(fromMethod));
    }else {
        method_exchangeImplementations(fromMethod, toMethod);
    }
}

- (id)safe_objectAtIndex:(NSUInteger)index {
    if (self.count-1 < index) {
        @try {
            return [self safe_objectAtIndex:index];
        }
        @catch (NSException *exception) {
            NSLog(@"------ %s Crash Because Method %s ------\n", class_getName(self.class), __func__);
            NSLog(@"%@", [exception callStackSymbols]);
            return nil;
        }
        @finally {
            
        }
    }else {
        return [self safe_objectAtIndex:index];
    }
}

@end

我们发现__NSArrayI才是NSArray真正的类
下面列举一些常用的类簇的“真身”

“真身”
NSArray __NSArrayI
NSMutableArray __NSArrayM
NSDictionary __NSDictionaryI
NSMutableDictionary __NSDictionaryM

下面这个示例是 通过交换NSMutableDictionary的setObject:forKey:方法,让调用这个方法时当参数object或key为空时不会抛出异常导致程序崩溃

#import "NSMutableDictionary+SafeMutableDictionary.h"

#import <objc/runtime.h>

@implementation NSMutableDictionary (SafeMutableDictionary)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class originalClass = NSClassFromString(@"__NSDictionaryM");
        Class swizzledClass = [self class];
        
        SEL originalSelector = @selector(setObject:forKey:);
        SEL swizzledSelector = @selector(safe_setObject:forKey:);
        
        Method originalMethod = class_getInstanceMethod(originalClass, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(swizzledClass, swizzledSelector);
        
        IMP originalIMP = method_getImplementation(originalMethod);
        IMP swizzledIMP = method_getImplementation(swizzledMethod);
        const char *originalType = method_getTypeEncoding(originalMethod);
        const char *swizzledType = method_getTypeEncoding(swizzledMethod);
        
        class_replaceMethod(originalClass,swizzledSelector,originalIMP,originalType);
        class_replaceMethod(originalClass,originalSelector,swizzledIMP,swizzledType);

    });
}

- (void)safe_setObject:(id)anObject forKey:(id)aKey {
    if (anObject && aKey) {
        [self safe_setObject:anObject forKey:aKey];
    }
    else {
        @try {
            [self safe_setObject:anObject forKey:aKey];
        }
        @catch (NSException *exception) {
            NSLog(@"------ %s Crash Because Method %s ------\n", class_getName(self.class), __func__);
            NSLog(@"%@", [exception callStackSymbols]);
        }
        @finally {
            if (aKey) {
                [(NSMutableDictionary *)self removeObjectForKey:aKey];
            }
        }
    }
}

在Method swizzling之后如何恢复?

首先来看一下使用Method swizzling最核心的其实也只做了两件事情:

  • class_addMethod添加一个新的方法, 可能是把其它类中实现的方法添加到目标类中, 也可能是把父类实现的方法添加一份在子类中, 可能是添加的实例方法, 也可能是添加的类方法, 总之就是添加了方法.
  • 交换IMP,交换方法的实现IMP,完成这个步骤除了使用method_exchangeImplementations这个方法外, 也可以是调用了method_setImplementation方法来单独修改某个方法的IMP, 或者是采用在调用class_addMethod方法中设定了IMP而直接就完成了IMP的交换, 总之就是对IMP的交换.

那我们来分别看一下这两件事情是否都还能恢复:

  • 对于class_addMethod, 我们首先想到的可能就是有没有对应的remove方法呢, 在Objective-C 1.0的时候有class_removeMethods这个方法, 不过在2.0的时候就已经被禁用了, 也就是苹果并不推荐我们这样做, 想想似乎也是挺有道理的, 本来runtime的接口看着就挺让人心惊胆战的, 又是添加又是删除总觉得会出岔子, 所以只能放弃remove的想法, 反正方法添加在那儿倒也没什么太大的影响.
  • 针对IMP的交换, 在Method Swizzling时做的交换动作, 如果需要恢复其实要做的动作还是交换回来罢了, 所以是可以做到的, 不过需要怎样做呢? 对于同一个类, 同一个方法, 可能会在不同的地方被多次做Method Swizzling, 所以要回退某一次的Method Swizzling, 我们就需要记录下来这一次交换的时候是哪两个IMP做了交换, 恢复的时候再换回来即可. 另一个问题是如果已经经过多次交换, 我们怎样找到这两个IMP所对应的Method呢, 还好runtime提供了一个class_copyMethodList方法, 可以直接取出Method列表, 然后我们就可以逐个遍历找到IMP所对应的Method了, 下面是对上一个示例添加恢复之后实现的代码逻辑:
#import @interface MySafeDictionary : NSObject
@end
 
static NSLock *kMySafeLock = nil;
static IMP kMySafeOriginalIMP = NULL;
static IMP kMySafeSwizzledIMP = NULL;
 
@implementation MySafeDictionary
 
+ (void)swizzlling {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        kMySafeLock = [[NSLock alloc] init];
    });
     
    [kMySafeLock lock];
     
    do {
        if (kMySafeOriginalIMP || kMySafeSwizzledIMP) break;
         
        Class originalClass = NSClassFromString(@"__NSDictionaryM");
        if (!originalClass) break;
         
        Class swizzledClass = [self class];
        SEL originalSelector = @selector(setObject:forKey:);
        SEL swizzledSelector = @selector(safe_setObject:forKey:);
        Method originalMethod = class_getInstanceMethod(originalClass, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(swizzledClass, swizzledSelector);
        if (!originalMethod || !swizzledMethod) break;
         
        IMP originalIMP = method_getImplementation(originalMethod);
        IMP swizzledIMP = method_getImplementation(swizzledMethod);
        const char *originalType = method_getTypeEncoding(originalMethod);
        const char *swizzledType = method_getTypeEncoding(swizzledMethod);
         
        kMySafeOriginalIMP = originalIMP;
        kMySafeSwizzledIMP = swizzledIMP;
         
        class_replaceMethod(originalClass,swizzledSelector,originalIMP,originalType);
        class_replaceMethod(originalClass,originalSelector,swizzledIMP,swizzledType);
    } while (NO);
     
    [kMySafeLock unlock];
}
 
+ (void)restore {
    [kMySafeLock lock];
     
    do {
        if (!kMySafeOriginalIMP || !kMySafeSwizzledIMP) break;
         
        Class originalClass = NSClassFromString(@"__NSDictionaryM");
        if (!originalClass) break;
         
        Method originalMethod = NULL;
        Method swizzledMethod = NULL;
        unsigned int outCount = 0;
        Method *methodList = class_copyMethodList(originalClass, &outCount);
        for (unsigned int idx=0; idx < outCount; idx++) {
            Method aMethod = methodList[idx];
            IMP aIMP = method_getImplementation(aMethod);
            if (aIMP == kMySafeSwizzledIMP) {
                originalMethod = aMethod;
            }
            else if (aIMP == kMySafeOriginalIMP) {
                swizzledMethod = aMethod;
            }
        }
        // 尽可能使用exchange,因为它是atomic的
        if (originalMethod && swizzledMethod) {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
        else if (originalMethod) {
            method_setImplementation(originalMethod, kMySafeOriginalIMP);
        }
        else if (swizzledMethod) {
            method_setImplementation(swizzledMethod, kMySafeSwizzledIMP);
        }
        kMySafeOriginalIMP = NULL;
        kMySafeSwizzledIMP = NULL;
    } while (NO);
     
    [kMySafeLock unlock];
}
 
- (void)safe_setObject:(id)anObject forKey:(id)aKey {
    if (anObject && aKey) {
        [self safe_setObject:anObject forKey:aKey];
    }
    else if (aKey) {
        [(NSMutableDictionary *)self removeObjectForKey:aKey];
    }
}
 
@end

注意: 这段代码的Method Swizzling和恢复都需要主动调用, 并且相比上面其它的示例, 这段代码还添加如锁机制来加之保护. 这个示例是以不同的类来实现的Method Swizzling和恢复, 如果是Category或者是类方法, 根据之前的示例也需要做相应的调整.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,792评论 1 32
  • 本文转载自:http://yulingtianxia.com/blog/2014/11/05/objective-...
    ant_flex阅读 914评论 0 1
  • 本文详细整理了 Cocoa 的 Runtime 系统的知识,它使得 Objective-C 如虎添翼,具备了灵活的...
    lylaut阅读 878评论 0 4
  • Runtime是一套比较底层的纯C语言API,包含了很多底层的C语言API。在我们平时编写的OC代码中,程序运行时...
    这个年纪的情愫丶阅读 728评论 5 3
  • Method Swizzling 在OC语言的runtime特性中,调用一个对象的方法就是给这个对象发送消息。是通...
    朴下柔阅读 310评论 0 0

友情链接更多精彩内容