用Runtime防止数组越界crash

利用runtime可以实现交换系统方法这一强大功能,下面将利用这一功能实现即使数组越界也不会crash这一功能。

#import "NSMutableArray+RZ.h"
#import 


@implementation NSMutableArray (RZ)

+ (void)load {
 
    //系统方法
    Method sysMethod = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(objectAtIndex:));
    //自定义方法
    Method safeMethod = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(safeObjectAtIndex:));

    //交换
    method_exchangeImplementations(sysMethod, safeMethod);

}


- (id)safeObjectAtIndex:(NSInteger)index {
    
    if (index > (self.count - 1)) {
//        NSAssert(NO, @"beyond the bound");
        return nil;
    }else if([self safeObjectAtIndex:index] == nil){
//        NSAssert(NO, @"beyond bounds for empty array");
        return nil;
    }else{
        return [self safeObjectAtIndex:index];
    }
    
}

NSAssert()只是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递条件表达式来断定是否属于Bug,满足条件返回真值,程序继续运行,如果返回假值,则抛出异常,并切可以自定义异常描述。NSAssert()是这样定义的:

define NSAssert(condition, desc)

condition是条件表达式,值为YES或NO;desc为异常描述,通常为NSString。当conditon为YES时程序继续运行,为NO时,则抛出带有desc描述的异常信息。NSAssert()可以出现在程序的任何一个位置。

另外.....

我的愿望是.......

世界和平.........

你可能感兴趣的:(用Runtime防止数组越界crash)