Learn Objective-C: Foreach Loop

Enumerating through the contents of a collection class is a very common activity. Collection classes in the Foundation framework include NSSet and NSArray. Enumerating is simply the act of going through the collection and getting every value inside—you might do this, for example, if you were doing the same thing to each one, like disabling the buttons in an NSArray of UIButtons. Normally, this would involve a for() loop, like this:

  1. NSArray *array = // Some array
  2. for (int i = 0; i < [array count]; i++)
  3.     [(UIButton *)[array objectAtIndex:i] setEnabled:NO];

This kind of syntax is so common that there is a shorthand way of doing it (known officially in Objective-C as fast enumeration:

  1. NSArray *array = // Some array
  2. for (UIButton *button in array)
  3.     button.enabled = NO;

The key is what goes inside the for() loop. You declare a variable of any type (to avoid a runtime crash, declare to be the type of variable in the array, such as the UIButton shown here, or if is more than one type, you could use id). Then you put the keyword in, followed by the name of the collection. Basically at this point, the new variable you created will be assigned to the “next” value in the collection at every iteration of the loop. In the body of the loop, you can do whatever you want to the variable. Note though that if you need to access the index of the object, you’ll have to go back to the original style.