containsObject - 为什么这不起作用?

Emi*_*mil 1 iphone nsnumber nsarray nsindexpath

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

我用这个代码:

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

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

任何人都可以看到为什么这样做不起作用?

ken*_*ytm 7

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

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

更好的解决方案是将NSNumber存储在阵列中.