1. 程式人生 > >工具類:防止陣列越界崩潰問題(NSArray 分類/runtime 用法3:交換方法)

工具類:防止陣列越界崩潰問題(NSArray 分類/runtime 用法3:交換方法)

#import <Foundation/Foundation.h>

@interface NSArray (Safe)

@end



#import "NSArray+Safe.h"
#import <objc/runtime.h>
@implementation NSArray (Safe)
//這個方法無論如何都會執行
+ (void)load {
    // 選擇器
    SEL safeSel = @selector(safeObjectAtIndex:);
    SEL unsafeSel = @selector(objectAtIndex:);

    Class class = NSClassFromString(@"__NSArrayI"
); // 方法 Method safeMethod = class_getInstanceMethod(class, safeSel); Method unsafeMethod = class_getInstanceMethod(class, unsafeSel); // 交換方法 method_exchangeImplementations(unsafeMethod, safeMethod); } - (id)safeObjectAtIndex:(NSUInteger)index { // 陣列越界也不會崩,但是開發的時候並不知道陣列越界 if
(index > (self.count - 1)) { // 陣列越界 NSAssert(NO, @"陣列越界了"); // 只有開發的時候才會造成程式崩了 return nil; }else { // 沒有越界 return [self safeObjectAtIndex:index]; } } @end