Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep track of index in fast enumeration

I want to get the index of the current object when using fast enumeration, i.e.

for (MyClass *entry in savedArray) { // What is the index of |entry| in |savedArray|? } 
like image 992
Shri Avatar asked Nov 13 '11 17:11

Shri


2 Answers

Look at the API for NSArray and you will see the method

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block 

So give that one a try

[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  }]; 
like image 50
Paul.s Avatar answered Sep 19 '22 23:09

Paul.s


I suppose the most blunt solution to this would be to simply increment an index manually.

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

Alternatively, you could just not use fast enumeration.

    for (NSUInteger indexInSavedArray = 0; indexInSavedArray < savedArray.count; indexInSavedArray++) {        [savedArray objectAtIndex:indexInSavedArray];      } 
like image 29
Josh Rosen Avatar answered Sep 18 '22 23:09

Josh Rosen