Search code examples
ios5for-in-loop

Using a for-in loop with NSInteger?


I have an NSMutableArray populated with NSIntegers. I need to loop through the array. I could do:

// given NSMutableArray *array of NSIntegers
NSUInteger n = [array count];
for (NSInteger i = 0; i < n; i++) {
  NSInteger x = [array objectAtIndex:i];
  // query SQLite WHERE id = x
}

However, it seems that a for (object in array) loop would be cleaner. iOS 5 does not accept NSIntegers or NSNumbers as objects in for-in loops. Should I loop through the array with NSObjects, casting the NSObject to an NSInteger during each iteration? Is there another way? Or is a for loop like the one above the cleanest solution to this problem?


Solution

  • In Objective-C you can use a for-in loop with NSNumber like this:

        NSArray *array = /*NSArray with NSNumber*/;
    
        for (NSNumber *n in array) {
            NSLog(@"i: %d", [n intValue]);
        }
    

    Check this out.