28

高速列挙を使用するときに現在のオブジェクトのインデックスを取得したい、つまり

for (MyClass *entry in savedArray) {
// What is the index of |entry| in |savedArray|?
}
4

5 に答える 5

65

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

}];
于 2011-11-13T18:13:52.473 に答える
9

これに対する最も率直な解決策は、単純にインデックスを手動でインクリメントすることだと思います。

NSUInteger indexInSavedArray = 0;
for (MyClass *entry in savedArray) {
   indexInSavedArray++;
 }

または、高速な列挙を使用できません。

    for (NSUInteger indexInSavedArray = 0; indexInSavedArray < savedArray.count; indexInSavedArray++) {
       [savedArray objectAtIndex:indexInSavedArray];
     }
于 2011-11-13T17:59:55.643 に答える
7

この質問はすでに回答されていますが、反復をカウントすることは、実際には iOS 開発者ライブラリのドキュメントに記載されている手法であることを付け加えておきます。

NSArray *array = <#Get an array#>;
NSUInteger index = 0;

for (id element in array) {
    NSLog(@"Element at index %u is: %@", index, element);
    index++;
}

派手なトリックがあると確信していましたが、そうではないと思います。:)

于 2012-01-09T02:53:23.630 に答える
0

簡単な観察: インデックスを -1 に初期化してから、++index を for ループの最初の行として配置すると、すべてのベースがカバーされません (誰かがインクリメントの前にコードをスリップしない場合)。

于 2013-05-15T20:19:01.397 に答える