ios开发之防数组越界

2017-02-25  本文已影响0人  飞扬的青春8780975

ios开发中,不免会遇到数组越界的问题,而当数组越界时往往会导致程序的崩溃,结局的方法之一就是在数组的分类中使用runtime机制来交换方法,当数组越界时返回nil,没有越界时返回原本的index.这样就能达到防止程序崩溃的问题.

  1. 创建数组的分类.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSArray (beyond)
@end
  1. 在.m文件中,利用runtime替换数组中的objectAtIndex:(NSUInteger)index等方法.在方法中判断是否越界,这样就可以实现防止崩溃
#import "NSArray+beyond.h"
@implementation NSArray (beyond)
//每次都会加载
+(void)load{
    [super load];
     //  替换不可变数组中的方法
    Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
    Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(__nickyTsui__objectAtIndex:));
    method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
    //  替换可变数组中的方法
    Method oldMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:));
    Method newMutableObjectAtIndex =  class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(mutableObjectAtIndex:));
    method_exchangeImplementations(oldMutableObjectAtIndex, newMutableObjectAtIndex);
}
-(id)__nickyTsui__objectAtIndex:(NSUInteger)index{
    if (index > self.count - 1 || !self.count){
        @try {
            return [self __nickyTsui__objectAtIndex:index];
        } @catch (NSException *exception) {
            //__throwOutException  抛出异常
            NSLog(@"数组越界...");
            return nil;
        } @finally {
            
        }
    }
    else{
        return [self __nickyTsui__objectAtIndex:index];
    }
}
-(id)mutableObjectAtIndex:(NSUInteger)index{
    if (index > self.count - 1 || !self.count){
        @try {
            return [self mutableObjectAtIndex:index];
        } @catch (NSException *exception) {
            //__throwOutException  抛出异常
            NSLog(@"数组越界...");
            return nil;
        } @finally {
            
        }
    }
    else{
        return [self mutableObjectAtIndex:index];
    }
}
上一篇下一篇

猜你喜欢

热点阅读