开发者

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

开发者 https://www.devze.com 2022-12-31 01:36 出处:网络
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 b

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...)


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消