How to loop through every element in an NSArray

- by

We can use something called Fast Enumeration for this, using a modified for loop:

// build an array
NSArray *myArray = [[NSArray alloc]initWithObjects:@"One", @"Two", @"Three", @"Four", nil];
// loop through every element (dynamic typing)
for (id tempObject in myArray) {
    NSLog(@"Single element: %@", tempObject);
}

You don’t have to use dynamic typing if you know the types of objects you’re using. In our example this would work just as well:

// build an array
NSArray *myArray = [[NSArray alloc]initWithObjects:@"One", @"Two", @"Three", @"Four", nil];
// loop through every element (static typing)
for (NSString *tempObject in myArray) {
    NSLog(@"Single element: %@", tempObject);
}

Fast Enumeration also works with NSDictionaries of course:

// build a dictionary
NSDictionary *myDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:@"One", @"1", @"Two",@"2", @"Three", @"3",nil];
// loop through it (dynamic typing)
for (id tempObject in myDictionary) {
    NSLog(@"Object: %@, Key: %@", [myDictionary objectForKey:tempObject], tempObject);
}


If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site witout any pesky ads! More details here.

Add your voice!

This site uses Akismet to reduce spam. Learn how your comment data is processed.