检查数组是否包含特定索引处的元素?

7
if (![[array objectAtIndex:indexPath.row] isEmpty]) {
   .... proceed as necessary                                 
}

indexPath.row 可以保存任何类型的对象,也可以为空。通常情况下,它是空的,因此当尝试在指定位置检索对象时会出现错误。我已经尝试了上述方法,但也不起作用。有没有正确的方法来检查这种情况?


当你说它是“空的”时,你指什么?这个数组不是很长吗?它包含NSNull吗?你不能将nilNULL插入到数组中,因此你需要澄清。 - user94896
我之前并不知道这个问题。我只是假设它是空的,因为它出现了故障。谢谢你提供的信息! - iamtoc
2个回答

21

如果不确定数组是否包含特定索引处的对象,就不应该调用 objectAtIndex:。而是应该先进行检查:

if (indexPath.row < [array count])

如果你在tableView中使用数组作为数据源,那么应该简单地返回[array count]作为行数。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [array count];
}

直接获取 indexPath.row 对应的对象,无需检查任何条件。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Other code
    NSObject *obj = [array objectAtIndex:indexPath.row];
    // Proceed with obj
}

1
运行得非常完美!你们太棒了! - iamtoc

6

使用[array count]方法:

if (indexPath.row < [array count])
{
   //The element Exists, you can write your code here
}

else 
{
   //No element exists at this index, you will receive index out of bounds exception and your application will crash if you ask for object at current indexPath.row.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接