ios開(kāi)發(fā)中,不免會(huì)遇到數(shù)組越界的問(wèn)題,而當(dāng)數(shù)組越界時(shí)往往會(huì)導(dǎo)致程序的崩潰,結(jié)局的方法之一就是在數(shù)組的分類中使用runtime機(jī)制來(lái)交換方法,當(dāng)數(shù)組越界時(shí)返回nil,沒(méi)有越界時(shí)返回原本的index.這樣就能達(dá)到防止程序崩潰的問(wèn)題.
- 創(chuàng)建數(shù)組的分類.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSArray (beyond)
@end
- 在.m文件中,利用runtime替換數(shù)組中的objectAtIndex:(NSUInteger)index等方法.在方法中判斷是否越界,這樣就可以實(shí)現(xiàn)防止崩潰
#import "NSArray+beyond.h"
@implementation NSArray (beyond)
//每次都會(huì)加載
+(void)load{
[super load];
// 替換不可變數(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ù)組越界...");
return nil;
} @finally {
}
}
else{
return [self __nickyTsui__objectAtIndex:index];
}
}
-(id)mutableObjectAtIndex:(NSUInteger)index{
if (index > self.count - 1 || !self.count){
@try {
return [self mutableObjectAtIndex:index];
} @catch (NSException *exception) {
//__throwOutException 拋出異常
NSLog(@"數(shù)組越界...");
return nil;
} @finally {
}
}
else{
return [self mutableObjectAtIndex:index];
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者