美文网首页
译 ios 使用运行时规避数组等越界导致程序崩溃

译 ios 使用运行时规避数组等越界导致程序崩溃

作者: 瞌睡树懒 | 来源:发表于2019-01-15 13:18 被阅读7次

    项目中经常遇到数组越界的情况,这是个很烦人的问题,并且面试中常遇到,就思考写了下如何避免这样的问题。
    首先我们获取数组元素的方式分为:

        NSArray *array = @[@1,@2];
        NSLog(@"arrary: %@",[array objectAtIndex:2]);
        NSLog(@"arrary: %@",array[2]);
        
        NSMutableArray *mutArray = [NSMutableArray arrayWithArray:@[@1,@2]];
        NSLog(@"NSMutableArray: %@",[mutArray objectAtIndex:2]);
        NSLog(@"NSMutableArray: %@",mutArray[2]);
    

    是的,通过objectAtIndex和[] 方式。

    然后我们是不是第一个想法就是写分类然后重写?
    嗯,我的确是试了一下,然后发现并没有用,系统这样提示我:

    Category is implementing a method which will also be implemented by its primary class

    WTF? 警告,说这里重写也没有用?那怎么办?
    而且还有一个问题就是,objectAtIndex方法很明确了,那么[] 这是个什么鬼?这也能用方法来表示?是的。
    有两种方式可以知道:
    第一种直接看错误:

    2017-12-29 19:25:36.510723+0800 OCTest[39152:4167702] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndexedSubscript:]: index 3 beyond bounds [0 .. 1]'
    *** First throw call stack:
    (
        0   CoreFoundation                      0x00007fff4150700b __exceptionPreprocess + 171
        1   libobjc.A.dylib                     0x00007fff680e5c76 objc_exception_throw + 48
        2   CoreFoundation                      0x00007fff41548514 _CFThrowFormattedException + 202
        3   CoreFoundation                      0x00007fff415b9201 -[__NSArrayI objectAtIndexedSubscript:] + 97
        4   OCTest                              0x0000000100000e55 main + 245
        5   libdyld.dylib                       0x00007fff68cd5115 start + 1
    )
    libc++abi.dylib: terminating with uncaught exception of type NSException
    

    我们人为越界了一下,发现了错误所在
    [__NSArrayI objectAtIndexedSubscript:]
    是的,这里告诉我们就是它发生了错误.
    第二种:

    在main.m文件中写下如下代码:
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            NSArray *array = @[@1,@2];
            NSLog(@"arrary: %@",[array objectAtIndex:2]);
            NSLog(@"arrary: %@",array[3]);
        }
        return 0;
    }
    
    然后通过命令行:
    clang -rewrite-objc main.m
    得到
    main.cpp
    拉倒最后:
    int main(int argc, const char * argv[]) {
        /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
            NSArray *array = ((NSArray *(*)(Class, SEL, ObjectType  _Nonnull const * _Nonnull, NSUInteger))(void *)objc_msgSend)(objc_getClass("NSArray"), sel_registerName("arrayWithObjects:count:"), (const id *)__NSContainer_literal(2U, ((NSNumber *(*)(Class, SEL, int))(void *)objc_msgSend)(objc_getClass("NSNumber"), sel_registerName("numberWithInt:"), 1), ((NSNumber *(*)(Class, SEL, int))(void *)objc_msgSend)(objc_getClass("NSNumber"), sel_registerName("numberWithInt:"), 2)).arr, 2U);
            NSLog((NSString *)&__NSConstantStringImpl__var_folders_2d_q947d5pn4z3dfyq0j4vqsq840000gn_T_main_9976d7_mi_0,((id (*)(id, SEL, NSUInteger))(void *)objc_msgSend)((id)array, sel_registerName("objectAtIndexedSubscript:"), (NSUInteger)1));
            NSLog((NSString *)&__NSConstantStringImpl__var_folders_2d_q947d5pn4z3dfyq0j4vqsq840000gn_T_main_9976d7_mi_1,((id (*)(id, SEL, NSUInteger))(void *)objc_msgSend)((id)array, sel_registerName("objectAtIndex:"), (NSUInteger)1));
        }
        return 0;
    }
    
    

    通过代码我们也知道了[]调用的方式:
    sel_registerName("objectAtIndexedSubscript:")
    里面的objectAtIndexedSubscript方法就是当我们使用[]的时候底层调用的方法。
    当然,它也无法重写。
    知道了原因,我们却无法重写,真是一个悲伤的故事。于是我找啊找啊,就找到了一种可以替代方法的方法。不给上,哥就不上了? 那也太怂了是吧。
    我找到的就是runtime中的替换方法。
    官方解释网址:

    https://developer.apple.com/documentation/objectivec/1418530-class_getinstancemethod

    Method class_getInstanceMethod(Class cls, SEL name);
    Returns a specified instance method for a given class.
    为给定的类返回指定的实例方法。
    我们先通过这个方法获取指定的实例方法
    https://developer.apple.com/documentation/objectivec/1418769-method_exchangeimplementations

    void method_exchangeImplementations(Method m1, Method m2);
    Exchanges the implementations of two methods.
    交换两种方法的实现。

    然后我们再自己实现个方法,这方法里面我们做一下规避操作。比如用try catch把异常给捕捉起来,然后打上日志。就不用担心会崩溃,也不知道哪里发生了错误。当然具体的方法要根据业务场景自我实现。
    下面的__NSArrayI 和__NSArrrayM分别代表不可变数组和可变数组的真实类型

    NSLog(@"type of array:%@",[array class]);
    NSLog(@"type of mutableArray:%@",[mArray class]);
    
    结果如下:
    2017-12-29 19:46:08.048887+0800 OCTest[39319:4202006] type of array:__NSArrayI
    2017-12-29 19:46:08.048905+0800 OCTest[39319:4202006] type of mutableArray:__NSArrayM
    
    

    通过runtime的method swizzling 交换方法的实现 提前判断方法的参数是否符合要求

    #import "NSArray+LXSRuntime.h"
    #import <objc/runtime.h>
    @implementation NSArray (LXSRuntime)
    +(void)load
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            // 替换不可变数组中的方法 objectAtIndex
            Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
            Method safeObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(safeObjectAtIndex:));
            method_exchangeImplementations(oldObjectAtIndex, safeObjectAtIndex);
            // 替换不可变数组中的方法 []调用的方法
            Method oldMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndexedSubscript:));
            Method safeMutableObjectAtIndex =  class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(safeObjectAtIndexedSubscript:));
            method_exchangeImplementations(oldMutableObjectAtIndex, safeMutableObjectAtIndex);
            
            // 替换可变数组中的方法 objectAtIndex
            Method oldMObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:));
            Method safeMObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(safeMutableObjectAtIndex:));
            method_exchangeImplementations(oldMObjectAtIndex, safeMObjectAtIndex);
            // 替换可变数组中的方法  []调用的方法
            Method oldMMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndexedSubscript:));
            Method safeMMutableObjectAtIndex =  class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(safeMutableObjectAtIndexedSubscript:));
            method_exchangeImplementations(oldMMutableObjectAtIndex, safeMMutableObjectAtIndex);
            
            Method sourceMethod2 = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(removeObjectAtIndex:));
            Method destMethod2 = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(safeRemoveObjectAtIndex:));
            
            method_exchangeImplementations(sourceMethod2, destMethod2);
            
            Method sourceMethod3 = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(insertObject:atIndex:));
            Method destMethod3 = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(safeInsertObject:atIndex:));
            
            method_exchangeImplementations(sourceMethod3, destMethod3);
            
            Method sourceMethod4 = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(replaceObjectAtIndex:withObject:));
            Method destMethod4 = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(safeReplaceObjectAtIndex:withObject:));
            
            method_exchangeImplementations(sourceMethod4, destMethod4);
            
        });
    }
    #pragma mark - 数组的安全处理
    - (id)safeObjectAtIndex:(NSUInteger)index{
        if (index > self.count - 1 || !self.count){
            @try {
                return [self safeObjectAtIndex:index];
            } @catch (NSException *exception) {
                NSLog(@"不可数组越界了");
                return nil;
            } @finally {
                
            }
        }
        else{
            return [self safeObjectAtIndex:index];
        }
    }
    
    - (id)safeObjectAtIndexedSubscript:(NSUInteger)index{
        if (index > self.count - 1 || !self.count){
            @try {
                return [self safeObjectAtIndexedSubscript:index];
            } @catch (NSException *exception) {
                NSLog(@"不可数组越界了");
                return nil;
            } @finally {
            }
        }
        else{
            return [self safeObjectAtIndexedSubscript:index];
        }
    }
    - (id)safeMutableObjectAtIndex:(NSUInteger)index{
        if (index > self.count - 1 || !self.count){
            @try {
                return [self safeMutableObjectAtIndex:index];
            } @catch (NSException *exception) {
                NSLog(@"可变数组越界了");
                return nil;
            } @finally {
                
            }
        }
        else{
            return [self safeMutableObjectAtIndex:index];
        }
    }
    
    - (id)safeMutableObjectAtIndexedSubscript:(NSUInteger)index{
        if (index > self.count - 1 || !self.count){
            @try {
                return [self safeMutableObjectAtIndexedSubscript:index];
            } @catch (NSException *exception) {
                NSLog(@"可变数组越界了");
                return nil;
            } @finally {
            }
        }
        else{
            return [self safeMutableObjectAtIndexedSubscript:index];
        }
    }
    
    -(void)safeRemoveObjectAtIndex:(NSInteger)index
    {
        if (self.count <= index) {
            NSLog(@"Runtime Warning:index %li out of bound",index);
            return;
        }
        
        [self safeRemoveObjectAtIndex:index];
    }
    -(void)safeInsertObject:(id)object atIndex:(NSInteger)index
    {
        if (!object) {
            NSLog(@"Runtime Warning:insert object can not be nil");
            return;
        }
        
        if (self.count < index) {
            NSLog(@"Runtime Warning:insert object at index %li out of bound",index);
            return;
        }
        
        [self safeInsertObject:object atIndex:index];
    }
    -(void)safeReplaceObjectAtIndex:(NSInteger)index withObject:(id)object
    {
        if (index >= self.count) {
            NSLog(@"Runtime Warning:index %li out of bound",index);
            return;
        }
        
        if (!object) {
            NSLog(@"Runtime Warning:object can not be empty");
            return;
        }
        
        [self safeReplaceObjectAtIndex:index withObject:object];
    }
    
    
    @end
    

    相关文章

      网友评论

          本文标题:译 ios 使用运行时规避数组等越界导致程序崩溃

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