3

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

great thanks. NSNumber still needs to be converted to NSInteger for some operations, but this is nice and clean
0

Mostly, you will not be allowed to have an NSMutableArray of NSUInteger (aka unsigned long) as it's not an objective-c object.

You may use the c style.

NSUInteger array[] = {value1,value2,value3};
int size = sizeof(array)/sizeof(array[0]);
for (int i=0; i<size; i++) {
   NSInteger value = array[i];
   // do whatever you want
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.