cocos2dbeginner
cocos2dbeginner

Reputation: 2207

How to do something with every second object in a NSArray? (iPhone)

I have a NSArray with many NSDictionaries. I'm using for to loop through it:

for (int i = 0; i < [myArray count]; i++) {

 }

Now I want to do something with every second object of the array. Let's say the array has an count of 5. Than it will do something with the 2nd, 4th and 5th object.

How can I do this?

for (int i = 0; i < [myArray count]; i++) {
           if //check if it is the second object 
     }

EDIT: Every second object and the last object if one will remain..

Upvotes: 0

Views: 1647

Answers (3)

Wilbur Vandrsmith
Wilbur Vandrsmith

Reputation: 5050

It might be better to use fast enumeration if you don't need the index:

BOOL odd = YES; 
for (id obj in ary) {
    odd = !odd;
    if (odd) continue;
    // do stuff
}

When odd is initialized, before the loop, consider the implicit index (i in a traditional for loop) to be -1. (Which is an odd number.) On the first iteration of the loop, the index is incremented to 0, and the odd flag is flipped to even (NO). The flag is not odd, so we run this iteration (index 0, 1st element). The next iteration increments the index to 1 (2nd element), and the flag is inverted to odd. Since the flag is odd, we skip this iteration. Execution continues like this until the end of the array.

Edit: The traditional for loop with an index is cleaner if you always want to operate on the last element. To do that here, you would need to track the index manually or repeat the loop contents after the loop.

Upvotes: 4

Sascha Galley
Sascha Galley

Reputation: 16091

Use the modulo operator:

if (i % 2 || (i == [myArray count] - 1)) {
    // do stuff
}

The modulo returns the remainder of the division i/2.
So if i is 0 (first item), it is 0 (==false).
If i is 1 (second item), it is 1 (==true).

To get your last element I added the (i == [myArray count] - 1) condition.

Upvotes: 0

yan
yan

Reputation: 20992

You can either increment by two during your loop increment or multiply by two when accessing.

i.e.:

for (int i = 0; i < [myArray count]; i += 2) {
  doStuff([myArray objectAtIndex:i]);
}

or

for (int i = 0; i < [myArray count]/2; i++) {
   doStuff([myArray objectAtIndex:i*2]);
}

Upvotes: 7

Related Questions