Reputation: 1619
I have an NSArray and I need to perform an action every two items on those two items. So I assume it is like a step value or something like it.
Start the loop, run my command on the first two items and then loop and run my command on the next two items - until the array is exhausted.
Any ideas on how to do this? I thought using a modulus but that can help with even odd, right? I need even and odd every 2.
My code that is hardwired to run on the first two items is below. I would like to add many more items and have the loop intelligently skip every two after the action and start the loop over again.
for (int i = 0; i < 2; i ++) {
shut01Path = CGPathCreateMutable();
shut01Path = CGPathCreateMutableCopy([self buildPathAtIndex:i].CGPath);
[arr_cgPathArray addObject:[UIBezierPath bezierPathWithCGPath:shut01Path]];
}
Upvotes: 0
Views: 863
Reputation: 1619
This code steps for me. Change s as needed.
int s = [array count]/4;
for (int i = 0; i < s; i ++) {
NSLog(@"%i",(i*s));
NSLog(@"%i",(i*s) + 1);
}
Upvotes: 0
Reputation: 8512
Simply increment the counter by two:
for (NSUInteger i = 0; i < array.count; i += 2) {
id even = array[i];
id odd = array[i + 1]; // Make sure the array has even count, otherwise this crashes.
}
Upvotes: 1
Reputation: 12782
You just need to check the index value at the beginning of each iteration of your for-loop. If your index value starts at zero and is incremented by 1 then you can check using modulo If the index % 2 is zero, you've got an even number. Otherwise odd number. Other conditions and indexing schemes may require fancier math or enable other conditional checks.
This is really standard C and general programming.
Upvotes: 0