高速列挙を使用するときに現在のオブジェクトのインデックスを取得したい、つまり
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];
}
この質問はすでに回答されていますが、反復をカウントすることは、実際には iOS 開発者ライブラリのドキュメントに記載されている手法であることを付け加えておきます。
NSArray *array = <#Get an array#>;
NSUInteger index = 0;
for (id element in array) {
NSLog(@"Element at index %u is: %@", index, element);
index++;
}
派手なトリックがあると確信していましたが、そうではないと思います。:)
簡単な観察: インデックスを -1 に初期化してから、++index を for ループの最初の行として配置すると、すべてのベースがカバーされません (誰かがインクリメントの前にコードをスリップしない場合)。