Adil's Personal Blog

Using octopress! A blogging framework for hackers.

Fast Enumeration in Objective-C

| Comments

Suppose you have collection of type e.g; NSArray, NSMutableArray, etc and you would like to iterate over all the elements one by one. One way to iterate over the collection would be to use for, while or do-while loop structure. But to use them, you have to know how many elements are in the collection to make sure you stay in the bounds of the collection object. Fast Enumeration help you to iterate the collection without worrying about this.

General Syntax of Enumeration

1
2
for (VariableType variable in collectionObject) {
}

The above syntax has 4 parts

  1. For loop structure.
  2. Declaring the type of objects collection have (VariableType variable).
  3. in, this will proceeded by the collection object.
  4. collectionObject, object holding the content.

Example:

1
2
3
4
5
NSArray *array = @[@"one", @"two", @"three", @"four"];

for (NSString *element in array) {
    NSLog(@"element: %@", element);
}

Output:

1
2
3
4
element: one
element: two
element: three
element: four

Comments