user593733
user593733

Reputation: 219

Implementing NSFastEnumeration on Custom Class

I have a class that inherits from NSObject. It uses an NSMutableArray to hold children objects, e.g. People using NSMutableArray *items to hold Person objects. How do I implement the NSFastEnumerator on items?

I have tried the following but it is invalid:

@interface People : NSObject <NSFastEnumeration>
{
    NSMutableArray *items;
}

@implementation ...

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
{
    if(state->state == 0)
    {
        state->mutationsPtr = (unsigned long *)self;
        state->itemsPtr = items;
        state->state = [items count];
        return count;
    }
    else
        return 0;
}

Upvotes: 6

Views: 2503

Answers (2)

ughoavgfhw
ughoavgfhw

Reputation: 39925

You are not using the NSFastEnumerationState structure properly. See NSFastEnumeration Protocol Reference and look at the constants section to see a description of each of the fields. In your case, you should leave state->mutationsPtr as nil. state->itemsPtr should be set to a C-array of the objects, not an NSArray or NSMutableArray. You also need to put the same objects into the array passed as stackbuf.

However, since you are using an NSMutableArray to contain the objects you are enumerating, you could just forward the call to that object:

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len {
    return [items countByEnumeratingWithState:state objects:stackbuf count:len];
}

Upvotes: 20

nevan king
nevan king

Reputation: 113777

There's an NSFastEnumeration protocol, but you are using the (non-existent) NSFastEnumerator protocol. Could that be the problem?

Upvotes: 1

Related Questions