Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Object-Oriented Objective-C Memory, Arrays and Loops, Oh My! NSArrays and For In Loops

what is wrong with my "for in" loop?

it says that i am not using a format specifier. Any suggestions will be much appreciated.

nsarray.mm
NSArray *drinks = [NSArray arrayWithObjects: @"juice",@"water",@"coffee", nil];
for (NSNumber *snacks in drinks){
  NSLog (@"juice");
  NSLog (@"water");
  NSLog (@"coffee");

}

1 Answer

Kyler Smith
Kyler Smith
10,110 Points

A for-in loop iterates over a list and stores the value it's currently dealing with in a temporary variable. In this case the temporary value is *snacks. The first problem is that it is labeled as an NSNumber, but the list is full of NSStrings. The type the list is iterating over should mirror the type in the list. Next, the NSLog statement is being logged explicitly but it should be implicitly logged.

NSArray *drinks = [NSArray arrayWithObjects: @"juice",@"water",@"coffee", nil];
for (NSString *snack in drinks) {
    NSLog(@"%@", drink); // only writing the statement once, but iterates through the list until it comes to nil.
}