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:


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

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

//While loop
x = 0;
while (x <= 4 ) {
     NSLog(@"x = %i", 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) {
//Release the array
[anArray release];


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


One thought on “Examples of Objective-C Loops

  1. Examples of Objective-C Loops…

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>