如何检查*number*是否在数组中

Emi*_*mil 4 arrays iphone xcode

非常基本的编程问题,我知道PHP有它的功能,但iPhone OS有吗?

我想检查当前indexPath是否是数组中的值.

PHP示例:

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

有谁知道如何在iOS中做同样的事情?

pre*_*io2 20

containsObject:
返回一个布尔值,指示接收器中是否存在给定对象.

- (BOOL)containsObject:(id)anObject

例如:

if ([arrayofNumbers containsObject:[NSNumber numberWithInt:516]])
    NSLog(@"WIN");
Run Code Online (Sandbox Code Playgroud)

或检查indexPath:

if ([arrayofIndexPaths containsObject:indexPath])
    NSLog(@"Yup, we have it");
Run Code Online (Sandbox Code Playgroud)

我应该澄清一个NSIndexPath不是数字而是一系列数字"代表嵌套数组集合树中特定节点的路径",如开发人员文档中更详细的解释.


Jef*_*f B 9

你想要containsObjectindexOfObject:

unsigned int myIndex = [myArray indexOfObject: [NSNumber numberWithInt: 3]];
if(myIndex != NSNotFound) {
     // Do something with myIndex
}
Run Code Online (Sandbox Code Playgroud)

要么:

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