项目中防止数据字典越界,无需更改任何代码.

如题,写了两个几个分类 github下载地址

https://github.com/JianWenXie/array-dict-Safe.h.git
//
//  NSArray+Safe.h
//  KVOTest
//
//  Created by StriEver on 16/7/29.
//  Copyright © 2016年 StriEver. All rights reserved.
//

#import 
@interface NSArray (Safe)

@end

//
//  NSArray+Safe.m
//  KVOTest
//
//  Created by StriEver on 16/7/29.
//  Copyright © 2016年 StriEver. All rights reserved.
//

#import "NSArray+Safe.h"
#import 
#import "NSObject+ImpChangeTool.h"
@implementation NSArray (Safe)
+ (void)load{
    static dispatch_once_t onceDispatch;
    dispatch_once(&onceDispatch, ^{
        [self SwizzlingMethod:@"objectAtIndex:" systemClassString:@"__NSArrayI" toSafeMethodString:@"st_objectAtIndex:" targetClassString:@"NSArray"];
        
         [self SwizzlingMethod:@"initWithObjects:count:" systemClassString:@"__NSPlaceholderArray" toSafeMethodString:@"initWithObjects_st:count:" targetClassString:@"NSArray"];
//        
        [self SwizzlingMethod:@"arrayByAddingObject:" systemClassString:@"__NSArrayI" toSafeMethodString:@"arrayByAddingObject_st:" targetClassString:@"NSArray"];
    });
}
- (id)st_objectAtIndex:(NSUInteger)index{
    //判断数组是否越界
    if (index >= [self count]) {
        NSLog(@"数组越界了");
        return nil;
    }
    return [self st_objectAtIndex:index];
}
- (NSArray *)arrayByAddingObject_st:(id)anObject {
    if (!anObject) {
         NSLog(@"插入空数据啦");
        return self;
    }
    return [self arrayByAddingObject_st:anObject];
}
- (instancetype)initWithObjects_st:(id *)objects count:(NSUInteger)count {
    NSUInteger newCount = 0;
    for (NSUInteger i = 0; i < count; i++) {
        if (!objects[i]) {
            break;
        }
        newCount++;
    }
    self = [self initWithObjects_st:objects count:newCount];
    return self;
}


@end

这个是对数组防错的一个分类,可还有可变数组,|字典|可变字典....

想到要复制这么多代码太累了,

我还是老老实实全部上传github上去吧.

大伙只需要把分类丢到自己项目中就可以搞定

https://github.com/JianWenXie/array-dict-Safe.h.git

你可能感兴趣的:(项目中防止数据字典越界,无需更改任何代码.)