6

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;
}
Nick Forge
  • 21,344
  • 7
  • 55
  • 78
user593733
  • 219
  • 3
  • 11
  • What is it that you are trying to do? If you just use [array count] you can get the count already, if you want to get the count of certain types of objects in the array you should use for(id object in array) <= which is fast enumeration – Antwan van Houdt Jan 28 '11 at 12:39
  • I have an instance on my People class in my app delegate let's say I want to be able to do this: for (Person *p in People) { NSLog(p); } – user593733 Jan 28 '11 at 14:52

2 Answers2

20

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];
}
ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123
1

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

nevan king
  • 112,709
  • 45
  • 203
  • 241
  • I have an instance on my People class in my app delegate let's say I want to be able to do this: for (Person *p in People) { NSLog(p); } – user593733 Jan 28 '11 at 14:47