在iOS開發中有時會遇到數組越界的問題,從而導致程序崩潰。為了防止程序崩潰,我們就要對數組越界進行處理。通過上網查資料,發現可以通過為數組寫一個分類來解決此問題。
基本思路:為NSArray寫一個防止數組越界的分類。分類中利用runtime將系統中NSArray的對象方法objectAtIndex:替換,然后對objectAtIndex:傳遞過來的下標進行判斷,如果發生數組越界就返回nil,如果沒有發生越界,就繼續調用系統的objectAtIndex:方法。
代碼:
.h文件:
#import
#import
@interface NSArray (beyond)
@end
.m文件:
#import "NSArray+beyond.h"
@implementation NSArray (beyond)
+ (void)load{
[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);
}
- (id)__nickyTsui__objectAtIndex:(NSUInteger)index{
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];
}
}
- (id)mutableObjectAtIndex:(NSUInteger)index{
if (index >self.count -1 || !self.count){
@try {
return [selfmutableObjectAtIndex:index];
} @catch (NSException *exception) {
//__throwOutException? 拋出異常
NSLog(@"數組越界...");
returnnil;
} @finally {
}
}
else{
return [selfmutableObjectAtIndex:index];
}
}