美文网首页iOS常用
iOS 利用runtime处理数组越界容错

iOS 利用runtime处理数组越界容错

作者: 邓布利多教授 | 来源:发表于2020-01-09 14:29 被阅读0次

    .h文件

    #import <Foundation/Foundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface NSArray (LYAarrayCategory)
    
    @end
    
    NS_ASSUME_NONNULL_END
    

    .m文件

    #import "NSArray+LYAarrayCategory.h"
    #import <objc/runtime.h>
    
    @implementation NSArray (LYAarrayCategory)
    
    #pragma mark - Override Base Funtion
    +(void)load{
        
        [super load];
        
        //获取要替换的系统方法
        Method sysMethod1 = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
        Method sysMethod2 = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndexedSubscript:));
        //添加自己的方法
        Method selfMethod1 = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(ly_objectAtIndex:));
        Method selfMethod2 = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(ly_objectAtIndexedSubscript:));
        
        //实现方法交换
        method_exchangeImplementations(sysMethod1, selfMethod1);
        method_exchangeImplementations(sysMethod2, selfMethod2);
        
    }
    
    #pragma mark - Action && Notification
    -(id)ly_objectAtIndex:(NSInteger)index{
        
        if (self.count - 1 < index) {
            
            @try {
                return [self ly_objectAtIndex:index];
            } @catch (NSException *exception) {
                
                NSLog(@"---------- %s Crash Because Method %s ----------\n",class_getName(self.class),__func__);
                NSLog(@"---------- %@",[exception callStackSymbols]);
                return nil;
                
            } @finally {
                NSLog(@"nothing to do");
            }
            
        }else{
            return [self ly_objectAtIndex:index];
        }
        
    }
    
    -(id)ly_objectAtIndexedSubscript:(NSInteger)index{
        
        if (self.count - 1 < index) {
            
            @try {
                return [self ly_objectAtIndex:index];
            } @catch (NSException *exception) {
                
                NSLog(@"---------- %s Crash Because Method %s ----------\n",class_getName(self.class),__func__);
                NSLog(@"---------- %@",[exception callStackSymbols]);
                return nil;
                
            } @finally {
                NSLog(@"nothing to do");
            }
            
        }else{
            return [self ly_objectAtIndex:index];
        }
        
    }
    
    @end
    

    相关文章

      网友评论

        本文标题:iOS 利用runtime处理数组越界容错

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