我们使用NSArray或者NSMutableArray时,通常调用
- (ObjectType)objectAtIndex:(NSUInteger)index;
来通过索引获取对象。但是在使用这个方法时经常会抛出越界的异常,例如定义一个数组,并获取指定下标的值:
NSUInteger index = 4;
NSArray *arr = [[NSArray alloc]initWithObjects:@"1",@"2",@"3", nil];
id obj = [arr objectAtIndex:index];
NSLog(@"object at index:%@",obj);```
这时会导致程序出错,错误日志:
>***** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 4 beyond bounds [0 .. 2]'**
就是我们经常遇到的数组越界问题,为了避免这种问题的发生,我们应该对要穿入的索引值进行判断,如果超出了数组的边界,就应该直接返回空值。代码如下:
NSUInteger index = 4;
NSArray *arr = [[NSArray alloc]initWithObjects:@"1",@"2",@"3", nil];
id obj = nil;
if (index > arr.count) {
obj = nil;
}else{
obj = [arr objectAtIndex:index];
}
NSLog(@"object at index:%@",obj);
运行结果:
>**object at index:(null)**
因此,我们如果需要避免数组越界发生,有必要对索引值进行一次判断,但如果在工程中每一处都加判断未免过于麻烦,因此我们可以写一个NSArray的category扩展类,并重写```objectAtIndex:(NSUInteger )index```方法。
- (id)safe_objectAtIndex:(NSUInteger )index{
if (index > self.count || index < 0) {
//index超出数组界限
return nil;
}
return [self objectAtIndex:index];
但同时我们应注意一个问题,如果通过这种方式强制性避免了越界导致的异常,可能会使工程中的其它部分受到一定程度的影响。因此应选择性地使用此方法。
github地址https://github.com/jojoting/TDSafeArray
网友评论