I'm looking for the standard idiom to iterate over an NSArray. My code needs to be suitable for OS X 10.4+.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
arrays can't contain nil.
Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.
NSSet is “toll-free bridged” with its Core Foundation counterpart, CFSetRef . See Toll-Free Bridging for more information on toll-free bridging. In Swift, use this class instead of a Set constant in cases where you require reference semantics.
The generally-preferred code for 10.5+/iOS.
for (id object in array) { // do something with object }
This construct is used to enumerate objects in a collection which conforms to the NSFastEnumeration
protocol. This approach has a speed advantage because it stores pointers to several objects (obtained via a single method call) in a buffer and iterates through them by advancing through the buffer using pointer arithmetic. This is much faster than calling -objectAtIndex:
each time through the loop.
It's also worth noting that while you technically can use a for-in loop to step through an NSEnumerator
, I have found that this nullifies virtually all of the speed advantage of fast enumeration. The reason is that the default NSEnumerator
implementation of -countByEnumeratingWithState:objects:count:
places only one object in the buffer on each call.
I reported this in radar://6296108
(Fast enumeration of NSEnumerators is sluggish) but it was returned as Not To Be Fixed. The reason is that fast enumeration pre-fetches a group of objects, and if you want to enumerate only to a given point in the enumerator (e.g. until a particular object is found, or condition is met) and use the same enumerator after breaking out of the loop, it would often be the case that several objects would be skipped.
If you are coding for OS X 10.6 / iOS 4.0 and above, you also have the option of using block-based APIs to enumerate arrays and other collections:
[array enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) { // do something with object }];
You can also use -enumerateObjectsWithOptions:usingBlock:
and pass NSEnumerationConcurrent
and/or NSEnumerationReverse
as the options argument.
The standard idiom for pre-10.5 is to use an NSEnumerator
and a while loop, like so:
NSEnumerator *e = [array objectEnumerator]; id object; while (object = [e nextObject]) { // do something with object }
I recommend keeping it simple. Tying yourself to an array type is inflexible, and the purported speed increase of using -objectAtIndex:
is insignificant to the improvement with fast enumeration on 10.5+ anyway. (Fast enumeration actually uses pointer arithmetic on the underlying data structure, and removes most of the method call overhead.) Premature optimization is never a good idea — it results in messier code to solve a problem that isn't your bottleneck anyway.
When using -objectEnumerator
, you very easily change to another enumerable collection (like an NSSet
, keys in an NSDictionary
, etc.), or even switch to -reverseObjectEnumerator
to enumerate an array backwards, all with no other code changes. If the iteration code is in a method, you could even pass in any NSEnumerator
and the code doesn't even have to care about what it's iterating. Further, an NSEnumerator
(at least those provided by Apple code) retains the collection it's enumerating as long as there are more objects, so you don't have to worry about how long an autoreleased object will exist.
Perhaps the biggest thing an NSEnumerator
(or fast enumeration) protects you from is having a mutable collection (array or otherwise) change underneath you without your knowledge while you're enumerating it. If you access the objects by index, you can run into strange exceptions or off-by-one errors (often long after the problem has occurred) that can be horrific to debug. Enumeration using one of the standard idioms has a "fail-fast" behavior, so the problem (caused by incorrect code) will manifest itself immediately when you try to access the next object after the mutation has occurred. As programs get more complex and multi-threaded, or even depend on something that third-party code may modify, fragile enumeration code becomes increasingly problematic. Encapsulation and abstraction FTW! :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With