2

我有一个 NSArray,我想在其中访问 NSArray 上的奇数和偶数对象,因为它们彼此持有不同的值。

实际上,这就是我目前正在做的一切

- (void)splitArray:(NSArray)array {
   for (id object in array) { // this itterates my array
      // do stuff in here
   }
}

我需要弄清楚如何捕捉偶数或奇数的物体......我在想像

- (void)splitArray:(NSArray)array {
   int i = 1;
   for (id object in array) { // this itterates my array
      if (i == even) {
        // do stuff here
      }
      else if (i == odd) {
       // do stuff here
      }
     i++
   }
}

只是我不知道在if ()

任何帮助将不胜感激

4

2 回答 2

6

要确定整数是偶数还是奇数,请使用模%运算符。如果index % 2 == 0是偶数,则为奇数。

您可以使用enumerateObjectsUsingBlock:循环遍历您的数组,而无需单独维护索引。

- (void)splitArray:(NSArray *)array {
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop) {
        if (index % 2 == 0) {
            // even stuff here
        } else {
            // odd stuff here
        }
     }];
}
于 2013-04-04T22:42:25.027 回答
1

如前所述,要么设置i为零并在循环中递增它,for要么只使用带有新 NSArray 语法的普通for循环(假设您使用的是最新版本的 Xcode)。另请注意,您应该传递一个NSArray *,而不是一个NSArray

- (void)splitArray:(NSArray*)array {
    for ( int i = 0; i < [array count]; i++ )
    {
        id object = array[i];

        if ( i % 2 == 0 ) {
            // even stuff here
        }
        else {
            //  odd stuff here
        }
    }
}
于 2013-04-04T22:34:15.040 回答