工具类:防止数组越界崩溃问题(NSArray 分类/runtime 用法3:交换方法)

来源:互联网 发布:智能马桶盖 知乎 编辑:程序博客网 时间:2024/06/06 14:51
#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
1 0