Examples of Objective-C Loops

Using loops to repeat actions in programming is a common task. Objective-C does this chore in more or less the same way as other programming languages. However, if you are still unfamiliar with the Objective-C syntax you may feel a little disoriented.So, to help out I wrote out some examples of for, for-each, do and while loops for you:

//Loops

//For loop
     for (int y = 0; y < 3; y++) {
     NSLog(@"y = %i", y);
}

//Do loop
x = 0;
do{
     NSLog(@"x = %i", x);
     x++;
}
while(x <= 4);

//While loop
x = 0;
while (x <= 4 ) {
     NSLog(@"x = %i", x);
     x++;
}

//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];

 

There you go – feel free to add any of your own examples on the comments below!

 

One Response to Examples of Objective-C Loops

  1. iPhoneKicks.com April 15, 2009 at 12:26 pm #

    Examples of Objective-C Loops…

    You’ve been kicked (a good thing) – Trackback from iPhoneKicks.com – iPhone SDK links, community driven…

Leave a Reply

Affiliate Policy Disclosure

Switch to our mobile site