1

我有一个数组,我正在尝试检查 indexPath(.row) 是否存在。

我使用这段代码:

if ([array containsObject:[NSNumber numberWithInt:indexPath.row]]){
    NSLog(@"Yep, it exists in there.");
}

该数组由数字 3、8 和 2 组成。索引路径在循环中加载从 0 到 8 的数字。

谁能明白为什么这不起作用?

4

1 回答 1

7

由于数组包含字符串,因此您应该与字符串进行比较。要创建数字字符串,请使用-stringWithFormat:. 所以:

if ([array containsObject:[NSString stringWithFormat:@"%d", indexPath.row]]){
    NSLog(@"Yep, it exists in there.");
}

更好的解决方案是将 NSNumber 存储在数组中。

于 2010-04-20T19:52:55.143 回答