Vincent Gable’s Blog

December 28, 2008

Fast Enumeration In Objective-C 1.0

Filed under: Cocoa,MacOSX,Objective-C,Programming,Sample Code | , ,
― Vincent Gable on December 28, 2008

I have used ForEach.h to do “Fast Enumeration” in Mac OS X 10.4 “Tiger”, without any problems. You must set the “C Language Dialect” in Xcode to C99 for it to work. Credit to Michael Tsai for the code, you can find other implementations of it on his website.

With ForEach.h you can do:

#import "ForEach.h"

foreach(thing, collection) {
   /*do stuff with thing*/
}

foreacht(NSString, name, allNames)
   ;//name is typed as an NSString*

With a large collection, the foreach macro should be faster then using NSEnumerator or objectAtIndex:, because it calls the nextObject function directly, without going through Objective-C’s message sending. I have not benchmarked it, because I haven’t had a reason to optimize the mechanics of my for-loops, so I don’t know by how much. But it should give you the fast in Fast Enumeration.

If you can’t use Objective-C 2.0’s Fast Enumeration (requires Leopard or, iPhone), then I highly recommend ForeEach.h.

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Powered by WordPress