Question

I'm trying to understand how to adopt the fast enumeration protocol (under iOS/objective C) for a class I'm creating. I read the section of Apple's docs, but... I don't quite get it!

Anyone have some sample code I could look at?

What I'm trying to do: I have an array of objects over which I want a sender to iterate. The sender wants to use a for-in construct. The catch is I don't want the sender to see all the objects in the array because some of them aren't valid in the context of the application.

In other words, I want my iterator to return a subset of objects in the array matching certain criteria.

I'd prefer not to create any new arrays in the process so as not to slow things down.

Was it helpful?

Solution

Apple's own FastEnumerationSample demonstrates it quite well. From the sounds of it, you may not have seen it yet.

There's also this blog post.

OTHER TIPS

Much better explanation here:

http://www.cocoawithlove.com/2008/05/implementing-countbyenumeratingwithstat.html

NB: Apple's source code is technically correct, but poorly explained, and mostly useless unless you enjoy playing "guess what the programmer was thinking / smoking that day".

Liekwise, Mike Ash's post is correct, and useful after you know how to do it, but terrible as a starting point.

I don't know what you mean by "sender wants to use a for-in construct". The outcome you're asking for would probably be better achieved by using indexesOfObjectsPassingTest:, which will give you an index set of all the items in your array that pass whatever test you have set up for it.

You could also use filteredArrayUsingPredicate: to derive a new array that's a subset of your original -- I know you said you didn't want to create any new arrays, but if you want to return a subset of your array, then you have to create a new array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top