Simple question about iterating 2 arrays in objective-c
I'm iterating a NSArray in objective-c with:
for (id object in array1) {
...
}
I now have another arra开发者_Go百科y2, and I need to access with the same index of the current array1.
Should I use another for statement ?
thanks
You have several options:
Use c-style for loop as Dan suggested
Keep track of current index in a separate variable in fast-enumeration approach:
int index = 0; for (id object in array1) { id object2 = [array2 objectAtIndex:index]; ... ++index; }
Use
enumerateObjectsUsingBlock:
method (OS 4.0+):[array1 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){ id obj2 = [array2 objectAtIndex:idx]; ... }];
If you need to share indexes, you can use a c style for loop:
for( int i = 0; i < [array1 count]; ++i )
{
id object2 = [array2 objectAtIndex:i];
//Do something with object2
}
精彩评论