首先加入一个小知识:

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了。

Runtime 函数 Swizzling 改变OC方法的调度顺序的更多相关文章

  1. iOS runtime探究(三): 从runtime開始理解OC的属性property

    你要知道的runtime都在这里 转载请注明出处 http://blog.csdn.net/u014205968/article/details/67639303 本文主要解说runtime相关知识, ...

  2. OC方法交换swizzle详细介绍——不再有盲点

    原文链接:https://www.cnblogs.com/mddblog/p/11105450.html 如果对方法交换已经比较熟悉,可以跳过整体介绍,直接看常见问题部分 整体介绍 方法交换是runt ...

  3. ES5——函数,对象,方法,this

    JS由表达式和语句组成 表达式:计算出一个值,但并不进行任何操作,不改变计算机运行状态 语句:包括 声明语句,赋值语句,控制结构 函数,对象,方法,this 数组和对象:是两个非常重要的数据类型 函数 ...

  4. [iOS Hybrid实践:UIWebView中Html中用JS调用OC方法,OC执行JS代码]

    原理: 1.JS调用OC 每次webview执行跳转时都会被iOS给拦截,执行下面函数获得系统允许. 因此可以根据跳转信息转给系统,执行相应功能,比如打开相册等. // 网页中的每一个请求都会被触发 ...

  5. 利用Objective-C运行时hook函数的三种方法

    版权声明:转载请注明出处:http://blog.csdn.net/hursing 方法一,hook已有公开头文件的类: 首先写一个Utility函数: #import <objc/runtim ...

  6. OC方法和文件编译

    OC方法和文件编译 一.OC方法 (一)对象方法 (1)对象方法以-开头如 -(void)xx; (2)对象方法只能又对象来调用 (3)对象方法中可以访问当前对象的成员变量 (4)调用格式   [对象 ...

  7. PHP使用feof()函数读文件的方法

    这篇文章主要介绍了PHP使用feof()函数读文件的方法,以实例形式对比了正确与错误的用法,阐明了feof()函数的使用技巧,需要的朋友可以参考下 本文实例讲述了PHP使用feof()函数读文件的方法 ...

  8. [Effective JavaScript 笔记]第28条:不要信赖函数对象的toString方法

    js函数有一个非凡的特性,即将其源代码重现为字符串的能力. (function(x){ return x+1 }).toString();//"function (x){ return x+ ...

  9. Objective-C Runtime 运行时之三:方法与消息

    基础数据类型 SEL SEL又叫选择器,是表示一个方法的selector的指针,其定义如下: typedef struct objc_selector *SEL; objc_selector结构体的详 ...

随机推荐

  1. 《JavaScript启示录》摘抄

    1.JavaScript预包装的9个原生的对象构造函数: Number(),String(),Boolean(),Object(),Array(),Function(),Data(),RegExp() ...

  2. ORMBase对象/关系型数据库映射在MVC中的应用

    ORM这个字眼在我们操作数据库的时候,是我们使用频率最高的.它到底是个什么东西呢,我们先来看看一些对它的含义解释. 对象/关系数据库映射(object/relational mapping(ORM)) ...

  3. Codeforces Round #237 (Div. 2)

    链接 A. Valera and X time limit per test:1 secondmemory limit per test:256 megabytesinput:standard inp ...

  4. 【NOIP 2014 DAY1 T3】飞扬的小鸟(DP)

    题目描述 Flappy Bird 是一款风靡一时的休闲手机游戏.玩家需要不断控制点击手机屏幕的频率来调节小鸟的飞行高度,让小鸟顺利通过画面右方的管道缝隙.如果小鸟一不小心撞到了水管或者掉在地上的话,便 ...

  5. [状压dp]POJ1185 炮兵阵地

    中文题 题意不再赘述 对于中间这个“P” 根据dp的无后效性 我们只需考虑前面的 就变成了 只需考虑: 也就是状压前两行 具体与HDOJ的4539类似: 看HDOJ 4539 仅仅是共存状态的判断不同 ...

  6. POJ - 2711 Leapin' Lizards

    题目大意: 在一个网格地图中有一些高度不同的石柱,一些石柱上站着一些蜥蜴,你的任务是让尽量多的蜥蜴逃到边界外. 每行每列中相邻石柱的距离为1,蜥蜴的跳跃距离是d,即蜥蜴可以跳到平面距离不超过d的任何一 ...

  7. 排序算法-冒泡排序(Bubble Sort)

    package com.wangzhu.sort; /** * 冒泡排序算法 * @ClassName: BubbleSort * @Description: TODO * @author wangz ...

  8. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-008-带参数的ADVICE

    一. 假设有情形如:cd里有很多轨,当播放音乐时,要统计每个音轨的播放次数,这些统计操作不应放在播放方法里,因为统计不是播放音乐的主要职责,这种情况适合应用AOP. 二. 1. package sou ...

  9. 【HDOJ】3652 B-number

    终于自己写出来一道数位DP啊.继续训练DP. /* 3652 */ #include <iostream> #include <sstream> #include <st ...

  10. 使用git批量删除分支

    要删除本地,首先要考虑以下三点 列出所有本地分支 搜索目标分支如:所有含有‘dev’的分支 将搜索出的结果传给删除函数 所以我们可以得到: git br |grep 'dev' |xargs git ...