containsObject - 为什么这不起作用?

时间:2010-04-20 18:49:39

标签: iphone nsarray nsnumber nsindexpath

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

我使用此代码:

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

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

有人能看出为什么这样做不起作用?

1 个答案:

答案 0 :(得分:7)

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

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

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

相关问题