Thursday, May 28, 2009

The For-Each Loop in Objective-C

Loops are the gears of a
programming language, they help move the program to the next step. 
A For-Each loop is generally used when you
want your program to do something to a collection of objects.
For example, this For-Each loop prints out each string in an
array of strings:

    //For each loop
    //Create an array and add elements to it
    NSMutableArray *anArray = [[NSMutableArray alloc] init];
    [anArray addObject:@"Element 1"];
    [anArray addObject:@"Element 2"];
    [anArray addObject:@"Element 3"];
   
    //Use a for each loop to iterate through the array
    for (NSString *s in anArray) {
        NSLog(s);
    }
   
    //Release the array
    [anArray release];


  That is it!

No comments: