版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337791
在iOS开发中有时会遇到数组越界的问题,从而导致程序崩溃。为了防止程序崩溃,我们就要对数组越界进行处理。通过上网查资料,发现可以通过为数组写一个分类来解决此问题。
基本思路:为NSArray写一个防止数组越界的分类。分类中利用runtime将系统中NSArray的对象方法objectAtIndex:替换,然后对objectAtIndex:传递过来的下标进行判断,如果发生数组越界就返回nil,如果没有发生越界,就继续调用系统的objectAtIndex:方法。
代码:
.h文件:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSArray (beyond)
@end
.m文件:
#import "NSArray+beyond.h"
@implementation NSArray (beyond)
superload;
// 替换不可变数组中的方法
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);
}
if (index >self.count -1 || !self.count){
@try {
return self__nickyTsui__objectAtIndex:index;
} @catch (NSException *exception) {
//__throwOutException 抛出异常
NSLog(@"数组越界...");
returnnil;
} @finally {
}
}
else{
return self__nickyTsui__objectAtIndex:index;
}
}
if (index >self.count -1 || !self.count){
@try {
return selfmutableObjectAtIndex:index;
} @catch (NSException *exception) {
//__throwOutException 抛出异常
NSLog(@"数组越界...");
returnnil;
} @finally {
}
}
else{
return selfmutableObjectAtIndex:index;
}
}
@
2018.06.01更新:
这里有一个防止数组越界崩溃的升级版,即使arrindex这种情况下产生的崩溃也能防止。
传送门:https://www.jianshu.com/writer#/notebooks/2349590/notes/28096621