user801255
user801255

Reputation: 607

Fast enumeration incomprehension

I found such code on this site:

 - (NSArray *) valueForKey:(id)key {
  NSMutableArray *retval = [NSMutableArray array];

  for (NSObject *object in self) {
    [retval addObject:[object valueForKey:key]];
  }

  return self;
}

Sorry for the newbie question, but I can't figure out what is fast enumerated there, as self is just an object, not a collection.

Upvotes: 1

Views: 199

Answers (3)

Paul.s
Paul.s

Reputation: 38728

If your example works then it means that self is an instance of a class that implements NSFastEnumeration. This is the protocol that needs to be adopted to allow fast enumeration.

You could for example create your own custom object and implement that protocol. Then inside that class you would be able to call

for (id obj in self) {

this would result in the following method being called on your class, which is defined in the NSFastEnumeration protocol

countByEnumeratingWithState:objects:count:

Upvotes: 0

Noah Witherspoon
Noah Witherspoon

Reputation: 57149

Any class that conforms to the NSFastEnumeration protocol can be enumerated with the in syntax. The code snippet you posted implies that the class also implements the -countByEnumeratingWithState:objects:count: method defined by the protocol, and that that method returns an array of NSObject instances to iterate over.

Upvotes: 4

Daniel A. White
Daniel A. White

Reputation: 191058

Its the for ( ... in ... ) loop.

NSMutableArray must conform to the NSFastEnumeration protocol.

See: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocFastEnumeration.html

Upvotes: 2

Related Questions