How to get the index of the current object in an iteration of NSEnumerator?

Question: How to get the index of the current object in an iteration of NSEnumerator?

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

+3
source share
2 answers

It is doubtful that using an integer counter in a loop forwill cause speed problems. Most likely, it will be slower to try to find the index of this object from the enumerator than just record the index yourself. If you want to get around re-sending messages, take a look at the NSArray method getObjects:range:.

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 will probably see only a minimal performance difference for incredibly large arrays, but don't underestimate the optimization under the hood. Even the documentation for getObjects:range:does not allow the use of this method for this purpose.

NSArray indexOfObject:will iterate over all items until a YESfrom message is returned isEqual:(which may include the following send message).

+2
source

, , . :

[array indexOfObject:currentObject];

( ). int.

+1

Source: https://habr.com/ru/post/1746184/


All Articles