iOS数组越界

2021-12-29  本文已影响0人  七秒归零

数组的越界处理:

    对NSArray添加分类,使用runtime的hook,替换对应的方法。

     self.dataArray[4] 的下标取值,对应的是数组的objectAtIndexedSubscript方法

    objectAtIndex的取值,对应的是数组的objectAtIndex方法

    使用runtime对两个方法进行拦截替换,就可以实现数据的异常处理。

    load方法中是使用GCD的单例方法,是避免用户错误调用出现多次交换,导致的错误。

+ (void)load{

    staticdispatch_once_tonceToken;

    dispatch_once(&onceToken, ^{

        MethodoriMethod =class_getInstanceMethod(NSClassFromString(@"__NSArrayI"),@selector(objectAtIndex:));

        MethodswiMethod =class_getInstanceMethod(NSClassFromString(@"__NSArrayI"),@selector(lg_objectAtIndex:));

        method_exchangeImplementations(oriMethod, swiMethod);

        MethodoriMethod1 =class_getInstanceMethod(NSClassFromString(@"__NSArrayI"),@selector(objectAtIndexedSubscript:));

        MethodswiMethod1 =class_getInstanceMethod(NSClassFromString(@"__NSArrayI"),@selector(lg_objectAtIndexedSubscript:));

        method_exchangeImplementations(oriMethod1,swiMethod1);

    });

}

// 交换的方法

- (id)lg_objectAtIndex:(NSUInteger)index{

    if(index >self.count-1) {

        NSLog(@"数组越界 -- ");

        returnnil;

    }

    return [self lg_objectAtIndex:index];

}

- (id)lg_objectAtIndexedSubscript:(NSUInteger)idx {

    if(idx >self.count-1){

        NSLog(@"取值越界了,请记录");

        returnnil;

    }

    return [self lg_objectAtIndexedSubscript:idx];

}

上一篇 下一篇

猜你喜欢

热点阅读