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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2677243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:17:31  来源:igfitidea点击:

How to check if *number* is in a array

iphonearraysxcode

提问by Emil

Pretty basic programming question, I know PHP have a function for it, but does the iPhone OS have one?

相当基本的编程问题,我知道 PHP 有一个功能,但 iPhone 操作系统有吗?

I want to check if the current indexPath is a value in an array.

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

PHP Example:

PHP 示例:

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

Does anybody know how to do the same thing in iOS?

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

回答by prendio2

containsObject:
Returns a Boolean value that indicates whether a given object is present in the receiver.

- (BOOL)containsObject:(id)anObject

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

- (BOOL)containsObject:(id)anObject

For example:

例如:

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

or to check an indexPath:

或检查索引路径:

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

I should clarify that an NSIndexPathis not a number but a series of numbers that "represents the path to a specific node in a tree of nested array collections" as explained in more detail in the developer documentation.

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

回答by Jeff B

You want containsObjector indexOfObject:

你想要containsObjectindexOfObject

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

Or:

或者:

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