Objective-C Fast Enumeration

Fast enumeration is the feature of Objective-C, helps in enumerating through a collection. Collections are the fundamental constructs. It is used to hold and manage the other objects. The main purpose of a collection is, it provides a common way to store and retrieve the object efficiently.

There are different types of collections in Objective-C. The most common collections in Objective-C are:

  • NSSet
  • NSDictionary
  • NSArray
  • NSMutableSet
  • NSMutableDictionary
  • NSMutableArray

Here is the general form to use fast enumeration in Objective-C:

for(classType variable in collectionObject )

Objective-C Fast Enumeration Example

Here is an example program, illustrating fast enumeration in Objective-C:

/* Objective-C Fast Enumeration - Example Program */
#import <Foundation/Foundation.h>

int main()
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSArray *array = [[NSArray alloc]
   initWithObjects:@"string1", @"string2",@"string3",nil];
   for(NSString *aString in array)
      NSLog(@"Value = %@",aString);
   [pool drain];
   return 0;

When we compile and execute the above program, it will produce the following output:

2014-10-15  06:26:22.835 demo[7426] Value = string1
2014-10-15 06:26:22.836 demo[7426] Value = string2
2014-10-15 06:26:22.836 demo[7426] Value = string3

Objective-C Online Test

« Previous Tutorial Next Tutorial »