美文网首页
解决数组为空崩溃

解决数组为空崩溃

作者: 40dd4b561abe | 来源:发表于2019-02-24 23:26 被阅读2次
    #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
    

    相关文章

      网友评论

          本文标题:解决数组为空崩溃

          本文链接:https://www.haomeiwen.com/subject/tnpiyqtx.html