美文网首页iOS底层技术
Runtime拦截可变数组replaceObjectAtInde

Runtime拦截可变数组replaceObjectAtInde

作者: wg刚 | 来源:发表于2019-06-10 16:41 被阅读0次
1、故意写一个相关崩溃代码
//拦截1
NSMutableArray *arr1 = @[@"1"].mutableCopy;
[arr1 replaceObjectAtIndex:5 withObject:@"2"];

//拦截2
NSMutableArray *arr2 = @[].mutableCopy;
[arr2 replaceObjectAtIndex:5 withObject:@"1"];

//拦截3
NSMutableArray *arr3 = @[@"1", @"2"].mutableCopy;
[arr3 replaceObjectAtIndex:0 withObject:nil];
2、方法交换拦截
#import "NSMutableArray+HuAvoidCrash.h"
#import <objc/message.h>

@implementation NSMutableArray (HuAvoidCrash)

+(void)load{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Class class = NSClassFromString(@"__NSArrayM");
        Method old = class_getInstanceMethod(class, @selector(replaceObjectAtIndex:withObject:));
        Method new = class_getInstanceMethod(class, @selector(hu_replaceObjectAtIndex:withObject:));

        if (old && new) {
            method_exchangeImplementations(old, new);
        }
        
    });
}

-(void)hu_replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject{
    
    if (self.count-1 >= index && anObject) {
        
        [self hu_replaceObjectAtIndex:index withObject:anObject];
    }else{
    }
}

@end
3、运行结果

发现拦截1成功,但是拦截2无效,最终奔溃。(但是也走进了这个拦截方法)

4、原因

看下图:断点走进了33行;导致崩溃
但是self确实0个元素;index是5;

为什么呢?

因为:NSUInteger的问题,NSUInteger是无符号的,没有负数

5、解决方案:
-(void)hu_replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject{
    
    if (self.count > index && anObject) {
        
        [self hu_replaceObjectAtIndex:index withObject:anObject];
    }else{
    }
}

相关文章

  • Runtime拦截可变数组replaceObjectAtInde

    1、故意写一个相关崩溃代码 2、方法交换拦截 3、运行结果 发现拦截1成功,但是拦截2无效,最终奔溃。(但是也走进...

  • 实用分类

    拦截所有UIButton事件,给UIControl添加分类 处理NSObject的Crash事件 可变数组元素不为...

  • 3大数据结构类之——不可变数组NSArray

    OC的数组同样分为不可变数组和可变数组,可变数组是不可变数组的子类,先来说不可变速数组 数组查询的相关方法 数组枚...

  • scala数据结构与可变不可变

    数组:可变与不可变不可变数组是指数组的长度是不可变的,但是数组对应的元素是可变的可变数组的长度和元素都可以改变 不...

  • 快速创建一个可变数组的方法

    如何快速创建一个可变数组 不可变空数组: @[] 可变空数组: @[].mutableCopy

  • 数组类常用操作方法

    一、数组 二、不可变数组(NSArray) 三、不可变数组的操作 四、可变数组(NSMutableArray)的操作

  • ios 数组

    创建不可变数组 创建不可变数组

  • iOS数组,字典,集合

    数组 1、固定数组 2、可变数组 3、数组转换 字典 1、不可变字典 2、可变字典 集合 //NSSet 是无序的...

  • swift基础-4-数组

    数组定义:OC:有值数组 空数组 不可变数组:NSArray可变数组:NSMutableArray swift:有...

  • 数组(可变、不可变)

    可变数组和不可变数组的创建和用法 如果可变数组定义为实例变量,应该先初始化再去用它 判断数组可不可变 不管是可变数...

网友评论

    本文标题:Runtime拦截可变数组replaceObjectAtInde

    本文链接:https://www.haomeiwen.com/subject/hfnzxctx.html