Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing NSFastEnumeration on Custom Class

Tags:

objective-c

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;
}
like image 251
user593733 Avatar asked Jan 28 '11 11:01

user593733


1 Answers

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];
}
like image 90
ughoavgfhw Avatar answered Sep 20 '22 17:09

ughoavgfhw