解决数组为空崩溃

2019-02-24  本文已影响2人  40dd4b561abe
#import "NSObject+NIL.h"

#import <objc/runtime.h>

@implementation NSObject (NIL)

+ (void)load
{
   Method objectAtIndex = class_getClassMethod(objc_getClass("NSArray"), @selector(arrayWithObjects:count:));
   Method my_objectAtIndex = class_getClassMethod( objc_getClass("NSArray"), @selector(my_arrayWithObjects:count:));
   method_exchangeImplementations(objectAtIndex,my_objectAtIndex);
   
   Method insertObject     = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(insertObject:atIndex:));
   Method my_insertObject  = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(my_insertObject:atIndex:));
   method_exchangeImplementations(insertObject,my_insertObject);
   
}


//数组添加空测试
- (void)my_insertObject:(id)anObject atIndex:(NSUInteger)index
{
   @try {
       [self my_insertObject:anObject atIndex:index];
   } @catch (NSException *exception) {
       NSDictionary *dic = [exception valueForKey:@"reserved"];
       NSString * str = dic[@"callStackSymbols"][5];
       str = [str substringFromIndex:[str rangeOfString:@"-"].location];
       str =[str substringToIndex:[str rangeOfString:@" +"].location];
       NSLog(@"%@里面的数组第%ld个元素为空", [str substringFromIndex:[str rangeOfString:@"-"].location],index);
   } @finally {
       
   }
}
//初始化数组为空测试
+ (instancetype)my_arrayWithObjects:(const id *)anObject count:(NSUInteger)index;
{
   @try {
      id d = [self my_arrayWithObjects:anObject count:index];
       return d;
   } @catch (NSException *exception) {
       int num = 0;
       for (int i = 0; i<index; i++) {
           if (*(anObject+i) == nil) {
               num = i;
           }
       }
       
       NSDictionary *dic = [exception valueForKey:@"reserved"];
       NSString * str = dic[@"callStackSymbols"][6];
       str = [str substringFromIndex:[str rangeOfString:@"-"].location];
       str =[str substringToIndex:[str rangeOfString:@" +"].location];
       NSLog(@"%@里面的数组第%d个元素为空", [str substringFromIndex:[str rangeOfString:@"-"].location],num);
       return nil;
   } @finally {
   }
}

@end
上一篇下一篇

猜你喜欢

热点阅读