標籤:越界 -- bsp cto sele art 不可變 article exception
1.
上面方法已經可以避免crash,為了避免冗餘的代碼,寫一個NSArray的分類,利用runtime替換NSArray的對象方法objectAtIndex:,在這裡進行判斷,捕獲異常:#import <Foundation/Foundation.h>@interface NSArray (Crash)@end/*** ---------------分割線--------------- ***/ #import "NSArray+Crash.h"#import <objc/runtime.h>@implementation NSArray (Crash)+ (void)load{ [super load]; //替換不可變數組方法 Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:)); Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtSafeIndex:)); method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex); //替換可變數組方法 Method oldMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:)); Method newMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(mutableObjectAtSafeIndex:)); method_exchangeImplementations(oldMutableObjectAtIndex, newMutableObjectAtIndex);}- (id)objectAtSafeIndex:(NSUInteger)index{ if (index > self.count - 1 || !self.count) { @try { return [self objectAtSafeIndex:index]; } @catch (NSException *exception) { NSLog(@"exception: %@", exception.reason); return nil; } }else { return [self objectAtSafeIndex:index]; }}- (id)mutableObjectAtSafeIndex:(NSUInteger)index{ if (index > self.count - 1 || !self.count) { @try { return [self mutableObjectAtSafeIndex:index]; } @catch (NSException *exception) { NSLog(@"exception: %@", exception.reason); return nil; } }else { return [self mutableObjectAtSafeIndex:index]; }}@end
http://blog.csdn.net/hero_wqb/article/details/78531218
第17月第7天 iOS 數組越界,防Crash處理