我想在使用快速枚举时获取当前对象的索引,即
for (MyClass *entry in savedArray) {
// What is the index of |entry| in |savedArray|?
}
for (MyClass *entry in savedArray) {
// What is the index of |entry| in |savedArray|?
}
查看NSArray的API,你会看到方法:
- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
那么试试这个吧。
[savedArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//... Do your usual stuff here
obj // This is the current object
idx // This is the index of the current object
stop // Set this to true if you want to stop
}];
NSUInteger indexInSavedArray = 0;
for (MyClass *entry in savedArray) {
indexInSavedArray++;
}
或者,你可以选择不使用快速枚举。
for (NSUInteger indexInSavedArray = 0; indexInSavedArray < savedArray.count; indexInSavedArray++) {
[savedArray objectAtIndex:indexInSavedArray];
}
[savedArray indexOfObject:entry];]
:) - Roman Temchenko这个问题已经得到了回答,但我想补充一点的是计数迭代实际上是iOS开发文库文档中提到的技术:
NSArray *array = <#Get an array#>;
NSUInteger index = 0;
for (id element in array) {
NSLog(@"Element at index %u is: %@", index, element);
index++;
}
NSUInteger index = -1;
然后在开始时递增索引吗? - Jimmery- (NSInteger) findElemenent:(NSString *)key inArray:(NSArray *)array
{
__block NSInteger index = -1;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isEqualToString:key]) {
*stop = YES;
index = idx;
}
}];
return index;
}
我刚刚遇到了一个相当严重的错误,因为我按照这里所有人建议的方式去做。也就是说,“创建一个索引变量,并在循环结束时将其递增”。
我建议应该避免这种方式,而应该遵循以下模式:
int index = -1;
for (a in b) {
index++;
//Do stuff with `a`
}
continue;
功能,它将跳过你循环结束时的最后一行index++
代码,导致你的索引计数错误!因此,我建议从-1开始递增,然后再执行其他操作。indexOfObject:
的人,这在存在重复条目时是行不通的。
*stop = YES
来使用(仅使用stop = YES
无效)。 - Tim