在工作中对于UITableView和UICollectionView的使用必不可少。
我们不难发现UITableView& UICollectionView的危险之处在于哪,在于执行其对于的代理方法的时候,我们所依赖的状态可能会发生变化,例如代码中的数据源被修改过,极有可能发生数组越界的异常。
方法一:
在代理方法内对越界进行判断,这种方法比较暴力,但是比较麻烦。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Item *item = nil;
if (indexPath.row < [_datasourceArray count]) {
item = [_datasourceArray objectAtIndex:indexPath.row];
}
}
方法二:
给NSArray扩展一个新方法
例如
#import "NSArray+LBJUtil.h"
@implementation NSArray (LBJUtil)
- (id)objectAtIndexJudge:(NSUInteger)index
{
if (index >= [self count]) {
return nil;
}
id value = [self objectAtIndex:index];
if (value == [NSNull null]) {
return nil;
}
return value;
}
@end