如何检查一个数字是否在数组中

4

这是一个基础的编程问题,我知道PHP有一个相应的函数,但是iPhone操作系统有没有类似的函数呢?

我想要检查当前的indexPath是否在数组中。

PHP示例:

<?php
$indexPath = 3;
$array = array("0", "1", "2", "3", "4");
if (in_array($indexPath, $array)) {
  // Do something
}
?>

有人知道在iOS上如何做相同的事情吗?


数字还是索引路径?索引路径由多个数字组成。 - kennytm
我认为字符数组可以被视为字符串,所以你不能使用类似于 $exists = strpos($array,$indexPath) 的方法吗? - Zachary Scott
2个回答

20

containsObject

返回一个布尔值,表示接收者中是否存在给定的对象。

- (BOOL)containsObject:(id)anObject

例如:

if ([arrayofNumbers containsObject:[NSNumber numberWithInt:516]])
    NSLog(@"WIN");

或者检查一个indexPath:

if ([arrayofIndexPaths containsObject:indexPath])
    NSLog(@"Yup, we have it");

我应该澄清一下,NSIndexPath不是一个数字,而是一系列数字,它们“表示嵌套数组集合中特定节点的路径”,如在开发人员文档中更详细地解释的那样。


更具体地说,在iPhone上,您应该查看NSIndexPath UITableView类别,其中定义了section和row的概念... NSIndexPath本身非常抽象,但在iPhone上,您真正需要使用它来获得这两个数字。 - Kendall Helmstetter Gelner
谢谢,但是它不起作用了。我有一个包含值为3、8和2的数组。我使用它来检查是否存在indexpath.row。如果([array containsObject:[NSNumber numberWithInt:indexPath.row]]){ NSLog(@"WIN"); } - Emil
你能展示一下你用来构建数组的代码吗?它是由NSNumbers还是ints组成的? - prendio2

9
您需要使用containsObjectindexOfObject方法:
unsigned int myIndex = [myArray indexOfObject: [NSNumber numberWithInt: 3]];
if(myIndex != NSNotFound) {
     // Do something with myIndex
}

或者:

if([myArray containsObject: [NSNumber numberWithInt: 3]]) {
    // Just need to know if it's there...
}

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