先上一段代碼
NSArray *testArray = @[@"a",@"b",@"c"];
NSLog(@"%@",[testArray objectAtIndex:3]);
NSLog(@"%@",testArray[3]);
在iOS中, 上述兩種取數(shù)組元素的方法都會(huì)導(dǎo)致程序崩潰, 稱為"數(shù)組越界", 那么在日常開發(fā)中,因?yàn)閿?shù)據(jù)的不確定性, 如果每次取指定index的元素前都要對(duì)數(shù)組的count進(jìn)行判斷,會(huì)非常繁瑣, 也會(huì)增加代碼量.
這里介紹一種簡(jiǎn)單的全局方法, 是通過tuntime的method swizzling實(shí)現(xiàn)的:
為NSArray添加一個(gè)category
#import <Foundation/Foundation.h>
///對(duì)數(shù)組越界進(jìn)行保護(hù)
// 適用于 objectAtIndex 的保護(hù) ,對(duì) array[index] 無效
// runtime實(shí)現(xiàn), 無需導(dǎo)入頭文件
@interface NSArray (DHArraySafe)
@end
#import "NSArray+ DHArraySafe.h"
#import <objc/runtime.h>
@implementation NSArray (DHArraySafe)
+ (void)load{
[super load];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ //方法交換只要一次就好
Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(__nickyTsui__objectAtIndex:));
method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
});
}
- (id)__nickyTsui__objectAtIndex:(NSUInteger)index{
if (index > self.count - 1 || !self.count){
@try {
return [self __nickyTsui__objectAtIndex:index];
} @catch (NSException *exception) {
//__throwOutException 拋出異常
return nil;
} @finally {
}
}
else{
return [self __nickyTsui__objectAtIndex:index];
}
}
@end
//mutableArray的對(duì)象也需要做方法交換
@interface NSMutableArray (DHArraySafe)
@end
@implementation NSMutableArray (DHArraySafe)
+ (void)load{
[super load];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ //方法交換只要一次就好
Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:));
Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(__nickyTsui__objectAtIndex:));
method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
});
}
- (id)__nickyTsui__objectAtIndex:(NSUInteger)index{
if (index > self.count - 1 || !self.count){
@try {
return [self __nickyTsui__objectAtIndex:index];
} @catch (NSException *exception) {
//__throwOutException 拋出異常
return nil;
} @finally {
}
}
else{
return [self __nickyTsui__objectAtIndex:index];
}
}
@end
注意:
1.對(duì)數(shù)組越界進(jìn)行保護(hù)
2.適用于 objectAtIndex 的保護(hù) ,對(duì) array[index] 無效
3.runtime實(shí)現(xiàn), 無需導(dǎo)入頭文件, 一次添加,對(duì)全局工程有效