SIGPIPE 13

Programming, automation, algorithms, macOS, and more.

Iterating an Array

Over at CocoaDev they are discussing how to efficiently iterate an NSArray.

I would really never ever think that the way you iterate an NSArray has any impact on the perceived performance of your program (granted you do not change the time complexity or do other stupid things), I would however think that it affects the perceived complexity of the source.

Here is the “ideal” iteration using an NSEnumerator.

NSEnumerator* enumerator = [array objectEnumerator];
while(id obj = [enumerator nextObject])
   NSLog("%@", obj);

Even with the help of TextMate’s placeholder savvy snippets, I really do not want that inserted each time I must run through all the elements of an array, so I created this macro:

#ifndef forall
#define forall(container,var) \
   for(id _enumerator = [container objectEnumerator], var; \
       var = [_enumerator nextObject]; )
#endif

It can be used like this:

forall(array, obj)
   NSLog("%@", obj);

And you may even change it to using objectAtIndex: or perhaps even CFArray functions, and you’ll see the benefits throughout your program :)

{{ numberOfCommentsTitle }}

{{ submitComment.success }}

Error Posting Comment

{{ submitComment.error }}