Runtime 函数 Swizzling 改变OC方法的调度顺序

简介: 首先加入一个小知识:SEL、Method、IMP的含义及区别在运行时,类(Class)维护了一个消息分发列表来解决消息的正确发送。每一个消息列表的入口是一个方法(Method),这个方法映射了一对键值对,其中键是这个方法的名字(SEL),值是指向这个方法实现的函数指针 implementation(IMP)。

首先加入一个小知识:

SEL、Method、IMP的含义及区别

在运行时,类(Class)维护了一个消息分发列表来解决消息的正确发送。每一个消息列表的入口是一个方法(Method),这个方法映射了一对键值对,其中键是这个方法的名字(SEL),值是指向这个方法实现的函数指针 implementation(IMP)。
伪代码表示:

Class {
      MethodList (
                  Method{
                      SEL:IMP;
                  }
                  Method{
                      SEL:IMP;
                  }
                  );
      };

Method Swizzling就是改变类的消息分发列表来让消息解析时从一个选择器(SEL)对应到另外一个的实现(IMP),同时将原始的方法实现混淆到一个新的选择器(SEL)。

 

对Swizzling方法封装

//

//  NSObject+Swizzling.h

//  Swizzling

//

//  Created by peter.zhang on 2016/12/14.

//  Copyright © 2016年 Peter. All rights reserved.

//

 

#import <Foundation/Foundation.h>

#import <objc/runtime.h>

 

@interface NSObject (Swizzling)

 

/**

 * Adds a new method to a class with a given name and implementation.

 *

 * @param originalSelector 原来的方法

 * @param swizzledSelector 替换成的方法

 *

*/

 

 + (void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector

                         bySwizzledSelector:(SEL)swizzledSelector;

 

@end

 

 

//

//  NSObject+Swizzling.m

//  Swizzling

//

//  Created by peter.zhang on 2016/12/14.

//  Copyright © 2016年 Peter. All rights reserved.

//

 

#import "NSObject+Swizzling.h"

 

@implementation NSObject (Swizzling)

 

 

 

+ (void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector bySwizzledSelector:(SEL)swizzledSelector{

    Class class = [self class];

    //原有方法

    Method originalMethod = class_getInstanceMethod(class, originalSelector);

    //替换原有方法的新方法

    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

    //先尝试給源SEL添加IMP,这里是为了避免源SEL没有实现IMP的情况

    BOOL didAddMethod = class_addMethod(class,originalSelector,

                                        method_getImplementation(swizzledMethod),

                                        method_getTypeEncoding(swizzledMethod));

    if (didAddMethod) {//添加成功:说明源SEL没有实现IMP,将源SEL的IMP替换到交换SEL的IMP

        class_replaceMethod(class,swizzledSelector,

                            method_getImplementation(originalMethod),

                            method_getTypeEncoding(originalMethod));

    } else {//添加失败:说明源SEL已经有IMP,直接将两个SEL的IMP交换即可

        method_exchangeImplementations(originalMethod, swizzledMethod);

    }

}

 

@end

 

-------------------------------以上是对Swizzling方法封装类别--------------------------------

runtime有很多用途:改变ViewController的生命周期、app热更新、改变系统方法调度(解决获取索引、添加、删除元素越界崩溃问题)等。今天主要说数组或者字典的越界crash问题。

 

啥都不是了,你把Swizzling方法封装类别添加到工程中:

以可变数组为例子:

//

//  NSMutableArray+Security.h

//  Swizzling

//

//  Created by peter.zhang on 2016/12/14.

//  Copyright © 2016年 Peter. All rights reserved.

//

 

#import <Foundation/Foundation.h>

 

@interface NSMutableArray (Security)

 

@end

 

 

 

//

//  NSMutableArray+Security.m

//  Swizzling

//

//  Created by peter.zhang on 2016/12/14.

//  Copyright © 2016年 Peter. All rights reserved.

//

 

#import "NSMutableArray+Security.h"

#import "NSObject+Swizzling.h"

 

@implementation NSMutableArray (Security)

 

+ (void)load {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(removeObject:) bySwizzledSelector:@selector(safeRemoveObject:) ];

        [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(addObject:) bySwizzledSelector:@selector(safeAddObject:)];

        [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(removeObjectAtIndex:) bySwizzledSelector:@selector(safeRemoveObjectAtIndex:)];

        [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(insertObject:atIndex:) bySwizzledSelector:@selector(safeInsertObject:atIndex:)];

        [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(objectAtIndex:) bySwizzledSelector:@selector(safeObjectAtIndex:)];

    });

}

 

- (void)safeAddObject:(id)obj {

    if (obj == nil) {

        NSLog(@"%s can add nil object into NSMutableArray", __FUNCTION__);

    } else {

        [self safeAddObject:obj];

    }

}

 

- (void)safeRemoveObject:(id)obj {

    if (obj == nil) {

        NSLog(@"%s call -removeObject:, but argument obj is nil", __FUNCTION__);

        return;

    }

    [self safeRemoveObject:obj];

}

 

- (void)safeInsertObject:(id)anObject atIndex:(NSUInteger)index {

    if (anObject == nil) {

        NSLog(@"%s can't insert nil into NSMutableArray", __FUNCTION__);

    } else if (index > self.count) {

        NSLog(@"%s index is invalid", __FUNCTION__);

    } else {

        [self safeInsertObject:anObject atIndex:index];

    }

}

 

- (id)safeObjectAtIndex:(NSUInteger)index {

    if (self.count == 0) {

        NSLog(@"%s can't get any object from an empty array", __FUNCTION__);

        return nil;

    }

    if (index > self.count) {

        NSLog(@"%s index out of bounds in array", __FUNCTION__);

        return nil;

    }

    return [self safeObjectAtIndex:index];

}

 

- (void)safeRemoveObjectAtIndex:(NSUInteger)index {

    if (self.count <= 0) {

        NSLog(@"%s can't get any object from an empty array", __FUNCTION__);

        return;

    }

    if (index >= self.count) {

        NSLog(@"%s index out of bound", __FUNCTION__);

        return;

    }

    [self safeRemoveObjectAtIndex:index];

}

 

@end

 

然后你在工程中用可变数组的增删改查都不会crash了。

 

相关文章
|
8月前
普通函数中的this指向问题解决方案call
普通函数中的this指向问题解决方案call
33 0
|
8月前
普通函数中的this指向问题解决方案apply
普通函数中的this指向问题解决方案apply
45 0
|
8月前
|
Java Kotlin
Kotlin 中初始化块、初始化的顺序、lateinit延迟初始化详解
Kotlin 中初始化块、初始化的顺序、lateinit延迟初始化详解
58 0
|
8月前
普通函数中的this指向问题解决方案apply
普通函数中的this指向问题解决方案apply
33 0
|
存储 Java
Java基础数组静态和动态初始化时机
Java基础数组静态和动态初始化时机
Java基础数组静态和动态初始化时机
java基础学习 数组,循环,变量,函数加载情况先后顺序,方法定义
java基础学习 数组,循环,变量,函数加载情况先后顺序,方法定义
java基础学习 数组,循环,变量,函数加载情况先后顺序,方法定义
|
存储 缓存 算法
JVM系列之:JVM是如何处理我们定义的对象生成代码
JVM系列之:JVM是如何处理我们定义的对象生成代码
79 0
JVM系列之:JVM是如何处理我们定义的对象生成代码
Runtime系列:super调用函数本质、isMemberOfClass与isKindOfClass的区别、综合分析【05】
Runtime系列:super调用函数本质、isMemberOfClass与isKindOfClass的区别、综合分析
101 0
Runtime系列:super调用函数本质、isMemberOfClass与isKindOfClass的区别、综合分析【05】
|
Swift 编译器
Swift - 实例对象调用协议方法优先级分析/ witness_methos witness_table分析
本文主要探究: 当一个类遵循了协议,且协议和类都有方法实现时,实例对象调用方法的优先顺序
Swift - 实例对象调用协议方法优先级分析/ witness_methos witness_table分析