xcode 如何获取数组中项目的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3478256/
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-09 03:30:59  来源:igfitidea点击:

How to get index of an item in an array

iphonexcodensmutablearray

提问by Linux world

I am having array called stored and I want to access their indexes so that I can select them individually to do my operations.

我有一个叫做存储的数组,我想访问它们的索引,以便我可以单独选择它们来执行我的操作。

If I want to print their indexes, what should I do?

如果我想打印他们的索引,我应该怎么做?

回答by jer

use NSArray's indexOfObject:method. Such as the following:

使用 NSArray 的indexOfObject:方法。例如以下内容:

NSUInteger fooIndex = [someArray indexOfObject: someObject];

回答by software is fun

int totalElements = [anArray count];
for(int i=0; i < totalElements; i++)
{
    data = [myArray indexOfObject:i];
}

The above code will give you the data if you pass in the index

如果你传入索引,上面的代码会给你数据

NSString *haystackText = @"Hello World";
int totalElements = [anArray count];
for(int i=0; i < totalElements; i++)
{
    BOOL result = [haystackText caseInsensitiveCompare:[myArray objectAtIndex:i] == NSOrderedSame;
    if(result)
    {
         NSUInteger fooIndex = [myArray indexOfObject: haystackText];
         return fooIndex;
    }
}

The code above will first find the element in the array and if it exists then return the index.

上面的代码将首先找到数组中的元素,如果存在则返回索引。

回答by Vandit Mehta

[array indexOfObject:object]

returns index of "object"

返回“对象”的索引

回答by Pradumna Patil

You can use indexOfObjectmethod to get the index of element.

您可以使用indexOfObject方法来获取元素的索引。

for example

例如

This will give you index of your object

这将为您提供对象的索引

  NSInteger index = [yourArray indexOfObject:objectName];

This worked for me. Hope this helps.

这对我有用。希望这可以帮助。

回答by ennuikiller

You can get a list of the indexes by using the count method which returns the number of elements in the array:

您可以使用 count 方法获取索引列表,该方法返回数组中的元素数:

int numElements = [myArray count];

I'll leave it as an exercise to print out the actual index values :)

我将把它作为一个练习来打印出实际的索引值:)

回答by Topher Fangio

This articlehas some great examples of how to iterate over an array. Then, inside the loop, you can use NSLogto print the index.

这篇文章有一些关于如何迭代数组的很好的例子。然后,在循环内部,您可以使用NSLog来打印索引。