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 UIButton
s. Normally, this would involve a for loop, like this:
NSArray *array = // Some array
for (int i = 0; i < [array count]; i++)
[(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:
NSArray *array = // Some array
for (UIButton *button in array)
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.
This post is part of the Learn Objective-C in 24 Days course.
Previous Lesson | Next Lesson |