When you implement fast enumeration, you do not have to return all the elements at once. Of course, all you get if you return them one at a time is fast enumeration syntax, without much of the performance benefit.
You could return a single element each time countByEnumeratingWithState:objects:count
is called, or you could return all the elements, or even just N elements.
For example, lets say you have a huge tree. You could use the stack buffer passed to you, and its length:
NSUInteger numItemsToReturn = MIN(100, lengthOfStackBuffer);
Then, you could continue your tree traversal up to numItemsToReturn
or until you reached the end of your tree.
The internal infrastructure will keep calling countByEnumeratingWithState:objects:count
until it has "seen" the right number of elements.
Note, however, that if you only return part of the data, you will have to store information in the state
so you know where to resume the next time. That's what extra
is for.
EDIT
Saw your comment on the original post... If you want to support fast-enumeration, then it's pretty easy, as mentioned above.
However, if you just want to traverse the tree to do stuff, you may want to consider an enumeration API. For example:
-(void)enumerateWithOptions:(MyTreeEnumerationOptions)options
usingBlock:^(id object, unsigned int level, BOOL isLeaf, BOOL *stop)block {
// In here, you can use the options to determine if you are doing
// pre/post depth first search, breadth-first, reverse, even concurrent.
// You also provide an easy way to communicate to the caller not only the
// object at this node, but the tree-depth of this node, whether it is a
// leaf, and anything else you want to communicate.
}
Users could then call:
[tree enumerateWithOptions:PreOrderDepthFirst
usingBlock:^(id object, unsigned int level, BOOL isLeaf, BOOL *stop) {
// Execute whatever code you want with this object...
// Set *stop = YES to abort the enumeration.
}];