一.最普通的方法,判断数组里边元素的个数:如
if
(indexPath.row < [_datasourceArray count]) {
item = [_datasourceArray objectAtIndex:indexPath.row];
}
优点:这种方法简单,易懂
缺点:
1>比较麻烦,一个程序里边有好多数组,每次用到都写一次,费时费力。。。
2>还时不时的漏写,忘写,出错以后还不好找,非常的蛋疼。。。
二.再次进化的方法是把 “if” 这里边的逻辑定义为一个宏或者是一个公共的方法,如:
1 /** 2 3 传入要遍历的数组和要取数组中第几个 4 */ 5 //代码为示意,只是一个思路,请大神们标示呵呵就好 6 - (id)arr:(NSArray*)arr row:(NSInteger)row{ 7 8 if (row < arr.count) { 9 10 return [arr objectAtIndex:row]; 11 }else{ 12 13 return nil; 14 } 15 }
这种思路比第一种的代码少了不少,不用每个地方都加 “if” 这块的逻辑,少了不少代码;
缺点:1>不一定记用有时候也要忘
2>多人开发的时候,别人也不一定知道你写了这样的方法,或者更会忘记调用这个方法
三.写一个分类(目前发现的比较好的方法)
1 @interface NSArray (SHYUtil) 2 3 4 /*! 5 @method objectAtIndexCheck: 6 @abstract 检查是否越界和NSNull如果是返回nil 7 @result 返回对象 8 */ 9 - (id)objectAtIndexCheck:(NSUInteger)index; 10 11 12 @end 13 14 15 16 17 #import "NSArray+SHYUtil.h" 18 19 20 @implementation NSArray (SHYUtil) 21 22 23 - (id)objectAtIndexCheck:(NSUInteger)index 24 { 25 if (index >= [self count]) { 26 return nil; 27 } 28 29 30 id value = [self objectAtIndex:index]; 31 if (value == [NSNull null]) { 32 return nil; 33 } 34 return value; 35 } 36 37 38 @end