【发布时间】:2023-03-18 00:23:01
【问题描述】:
如何在 Objective-c 中的“for (id item in items)”循环中获取数组索引?以 NSArray 或 NSMutableArray 为例。
例如:
for (id item in items) {
// How to get item's array index here
}
【问题讨论】:
标签: objective-c
如何在 Objective-c 中的“for (id item in items)”循环中获取数组索引?以 NSArray 或 NSMutableArray 为例。
例如:
for (id item in items) {
// How to get item's array index here
}
【问题讨论】:
标签: objective-c
或者,您可以使用-enumerateObjectsUsingBlock:,它将数组元素和相应的索引作为参数传递给块:
[items enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop)
{
…
}];
奖励:对数组元素并发执行块操作:
[items enumerateObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id item, NSUInteger idx, BOOL *stop)
{
…
}];
【讨论】:
我能想到的唯一方法是:
NSUInteger count = 0;
for (id item in items)
{
//do stuff using count as your index
count++;
}
或者,您可以使用NSArray 的indexOfObject: 消息来获取索引:
NSUInteger index;
for (id item in items)
{
index = [items indexOfObject:item];
//do stuff using index
}
【讨论】:
for(NSUInteger ix = 0;... 循环?
NSUInteger 代替int 作为索引变量。您不知道数组中有多少项目 - 以防万一。 ;)