直接上代码
//
// NSArray+OOBKit.h
// UITableViewBlockDemo
//
// Created by LT on 16/11/15.
// Copyright © 2016年 LT. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSArray (OOBKit)
/**
检查数组是否越界
@param index 角标
@return 检查是否越界和NSNull如果是返回nil
*/
- (id)objectAtIndexCheck:(NSUInteger)index;
@end
@interface NSMutableArray (OOBKit)
/**
检查可变数组是否越界
@param index 角标
@return 检查是否越界和NSNull如果是返回nil
*/
- (id)objectAtIndexCheck:(NSUInteger)index;
@end
//
// NSArray+OOBKit.m
// UITableViewBlockDemo
//
// Created by LT on 16/11/15.
// Copyright © 2016年 LT. All rights reserved.
//
#import "NSArray+OOBKit.h"
@implementation NSArray (OOBKit)
- (id)objectAtIndexCheck:(NSUInteger)index
{
if (index >= [self count]) {
return nil;
}
id value = [self objectAtIndex:index];
if (value == [NSNull null]) {
return nil;
}
return value;
}
@end
@implementation NSMutableArray (OOBKit)
- (id)objectAtIndexCheck:(NSUInteger)index
{
if (index >= [self count]) {
return nil;
}
id value = [self objectAtIndex:index];
if (value == [NSNull null]) {
return nil;
}
return value;
}
@end
使用示例
#import "NSArray+OOBKit.h"
NSArray *arr=@[@"1",@"2",@"3"];
NSLog(@"item=%@",[arr objectAtIndexCheck:3]);
NSMutableArray *arr2=[NSMutableArray arrayWithObjects:@"1",@"2",@"3", nil];
NSLog(@"item2=%@",[arr2 objectAtIndexCheck:3]);
访问越界数据是不会崩溃并返回nil
Paste_Image.png