ios 数组越界奔溃库_iOS中防止数组越界之后发生崩溃
在iOS開發(fā)中有時會遇到數(shù)組越界的問題,從而導(dǎo)致程序崩潰。為了防止程序崩潰,我們就要對數(shù)組越界進行處理。通過上網(wǎng)查資料,發(fā)現(xiàn)可以通過為數(shù)組寫一個分類來解決此問題。
基本思路:為NSArray寫一個防止數(shù)組越界的分類。分類中利用runtime將系統(tǒng)中NSArray的對象方法objectAtIndex:替換,然后對objectAtIndex:傳遞過來的下標進行判斷,如果發(fā)生數(shù)組越界就返回nil,如果沒有發(fā)生越界,就繼續(xù)調(diào)用系統(tǒng)的objectAtIndex:方法。
代碼:
.h文件:
#import
#import
@interface NSArray (beyond)
@end
.m文件:
#import "NSArray+beyond.h"
@implementation NSArray (beyond)
+ (void)load{
[superload];
//? 替換不可變數(shù)組中的方法
Method oldObjectAtIndex =class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(objectAtIndex:));
Method newObjectAtIndex =class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(__nickyTsui__objectAtIndex:));
method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
//? 替換可變數(shù)組中的方法
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(@"數(shù)組越界...");
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(@"數(shù)組越界...");
returnnil;
} @finally {
}
}
else{
return [selfmutableObjectAtIndex:index];
}
}
總結(jié)
以上是生活随笔為你收集整理的ios 数组越界奔溃库_iOS中防止数组越界之后发生崩溃的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Toad for Oracle9.7中导
- 下一篇: Struts2中s:iterator/s