Let’s say I have three arrays of same size. I have to do something with all objects. If I would use a standard C array, I would write something like
for (i = 0; i < size; i++) {
doSomething(array1[i]); // or [[array1 objectAtIndex:i] doSomething];
doSomethingElse(array2[i]); // or [[array2 objectAtIndex:i] doSomethingElse];
doSomethingReallySpecial(array3[i]); // or [[array3 objectAtIndex:i] doSomethingReallySpecial];
}
With Objective C we got more ways to cycle through objects in NSArray: fast enumeration, block-based enumeration and using enumerators. Which one should I use and why? What’s the difference?
Edit
Actually this question may be formulated like this: if one needs to use the index of an item of an array, which enumeration should be used?
You should use the one that most clearly expresses the intent of your code to readers of the code. Unless you have identified this loops as a significant performance bottleneck, ability to maintain your code is far more important.
That said, fast enumeration alone (i.e
for(id i in array)) does not provide the index. If you don’t want to use a C-style loop,-[NSArray enumerateObjectsUsingBlock:]provides both the current item and the index and could be used to zip multiple arrays. I suspect, that for multiple arrays, the C-style approach will be often be effectively equivalent in performance—and perhaps clearer to the reader, but you should profile it to be sure.What you’re looking for is a common idiom in functional programming and could certainly be implemented on top of GCD using blocks, but I don’t know of any implementations.