开发者

Simple question about iterating 2 arrays in objective-c

开发者 https://www.devze.com 2023-03-04 23:04 出处:网络
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.

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:

  1. Use c-style for loop as Dan suggested

  2. 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;
    }
    
  3. 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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消