3

Question: How do I get the index of the current Object in an NSEnumerator iteration?

(I don't want to keep track of things using an integer counter or use a for loop due to speed reasons. I did it before I just cannot remember how I did it...)

RexOnRoids
  • 14,002
  • 33
  • 96
  • 136
  • I would be very surprised if an integer counter affected the speed of your loop. Unless you are iterating billions of items, a simple counter isn’t going to have any noticeable impact. – Nate May 19 '10 at 13:50

2 Answers2

2

It is doubtful that using an integer counter in a for loop will cause speed problems. It is more likely to be slower to try and find the index of a given object from an enumerator than it is to just keep a record of the index yourself. If you want to bypass repeated message dispatch, have a look at NSArray's getObjects:range: method.

size_t count = [myArray count];
id *objects = calloc(count, sizeof(id));

[myArray getObjects:objects range:NSMakeRange(0, count)];

// if you have a very large count, you'll save doing an
// "objectAtIndex:" for each item.

for (int i = 0; i < count; i++)
    [objects[i] doSomething];

free(objects);

You'll probably only see a minimal performance difference for incredibly large arrays, but don't underestimate the optimisations under the hood. Even the documentation for getObjects:range: discourages using this technique for this purpose.

NSArray's indexOfObject: will iterate over all the elements until one returns YES from isEqual: message (which may include further message sending).

dreamlax
  • 93,976
  • 29
  • 161
  • 209
1

You are asking for an index, so we can assume that you are using an array. If so:

[array indexOfObject:currentObject];

will work for most cases (but not all). It would be faster overall to switch to using a normal for loop with an int counter, however.

Paul Lynch
  • 19,769
  • 4
  • 37
  • 41