Implementing NSFastEnumeration

Christiaan Hofman <[email protected]>
Newsgroups gmane.comp.macosx.devel
Message-ID <[email protected]>
I've been reading the documentation on NSFastEnumeration (both the  
docs on the protocol and the section in the Objective-C 2.0  
Programming Language guide). But it is really cryptic and misses most  
of the relevant information to help in implementing it. The Obj-C 2.0  
guide only mentions how to use it. And the NSFastEnumeration doc only  
has some truly useless descriptions of its rather confusing variables.  
For instance, saying that state->itemsPtr is "A C array of objects" is  
about the most useless comment I've ever seen. And I've also not been  
able to find any (Apple) sample code that implements this. Perhaps  
someone can give a link if he has found one?

An important question I have is: which variable should eventually hold  
the objects to return? As the NSFastEnumeration doc says that stackbuf  
is "A C array of objects over which the sender is to iterate", which  
would suggest that that's where the objects should be returned.  
However I saw this blog at <http://cocoawithlove.com/2008/05/implementing-countbyenumeratingwithstat.html 
 > that has some samples that suggest that the real place to return  
the objects is in state->itemsPtr. However from the docs I cannot  
possibly get a clue what that variable is actually used for.

So perhaps someone can give me some idea what is really meant. Also  
some (more) links to (Apple sanctioned) sample code could be helpful.

To be a bit more concrete, I have an object that wraps an NSArray of  
keys and an object (lets say a dictionary for the sake of the  
argument) containing the data looked up by key. I want to implement  
NSFastEnumeration so that it enumerates the objects looked up by key,  
in the order of the keys in the array. For instance, let's say I have  
the following to support traditional enumeration:

@interface LookupArray : NSArray {
	NSArray *keys;
	NSDictionary *values;
}
...
@end

@implementation LookupArray
...
- (NSUInteger)count {
	return [keys count];
}
- (id)objectAtIndex:(NSUInteger)i {
	return [values objectForKey:[keys objectAtIndex:i]];
}
@end

thanks,
Christiaan
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.