Shr*_*hri 28 cocoa-touch objective-c fast-enumeration
我想在使用快速枚举时得到当前对象的索引,即
for (MyClass *entry in savedArray) {
// What is the index of |entry| in |savedArray|?
}
Run Code Online (Sandbox Code Playgroud)
Pau*_*l.s 65
查看NSArray的API ,您将看到该方法
- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
Run Code Online (Sandbox Code Playgroud)
所以试一试
[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
}];
Run Code Online (Sandbox Code Playgroud)
我认为最直接的解决方案是简单地手动增加索引.
NSUInteger indexInSavedArray = 0;
for (MyClass *entry in savedArray) {
indexInSavedArray++;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以不使用快速枚举.
for (NSUInteger indexInSavedArray = 0; indexInSavedArray < savedArray.count; indexInSavedArray++) {
[savedArray objectAtIndex:indexInSavedArray];
}
Run Code Online (Sandbox Code Playgroud)
这个问题已经得到解答了,但我想我会补充说,计数迭代实际上是iOS Developer Library文档中提到的技术:
NSArray *array = <#Get an array#>;
NSUInteger index = 0;
for (id element in array) {
NSLog(@"Element at index %u is: %@", index, element);
index++;
}
Run Code Online (Sandbox Code Playgroud)
我确信会有一个奇特的伎俩,但我猜不是.:)
| 归档时间: |
|
| 查看次数: |
11584 次 |
| 最近记录: |