objective-ccocoafast-enumeration

How to implement the NSFastEnumeration protocol?


I have a class and I want my class to confirm to the NSFastEnumeration Protocol. I've read the documentation but it's not really clear. Can someone please tell me what the protocol method should return and how it works?


Solution

  • Apple's FastEnumerationSample shows you what to do, but here's a breakdown.

    The sole NSFastEnumeration method, countByEnumeratingWithState:objects:count:, returns chunks of the collection. It's executed whenever more items are needed, until it indicates that there are no more items by returning 0. A chunk is passed as a C array of ids.

    Within the method, the state parameter holds most (if not all) of the data you'll be using. You'll need to set state->itemsPtr and update state->state with each separate invocation of countByEnumeratingWithState:objects:count:. Here's a brief description of each field of NSFastEnumerationState:

    You can set state->state and any element of state->extra to whatever you wish; they're provided solely for your convenience, and do not affect Cocoa. state->itemsPtr, *state->mutationsPtr and the value returned by the method, however, do affect Cocoa.

    As for the two other method parameters, stackbuf is an array that Cocoa provides to hold items. Its use is optional, but if you don't use it, you'll have to allocate storage space for state->itemPtr. If you use it, set state->itemsPtr to stackbuf with each invocation. len is the length of stackbuf, the maximum number of items that you'll be able to store in it.

    Further reading: