4

There is the enumerateWithBlock method of NSArray, but I need to enumerate in a reverse order, is there a block for doing that, or do I have to use for loop instead, not even the fast loop, but the traditional for (int i = array.count - 1 ; i >= 0 ; i--) one?

Thanks!

0

2 Answers 2

19

You can use enumerateObjectsWithOptions:usingBlock: passing NSEnumerationReverse as the options parameter.

2
  • Is there any option for limit the loop to a maximum number? Say if I have 100 elements and I only want to loop through the last N?
    – hzxu
    Nov 9, 2012 at 4:16
  • @hzxu, There's no option to do that, but in the block, you have the idx property and the BOOL *stop, so you could set *stop to YES after you reach a certain index value.
    – rdelmar
    Nov 9, 2012 at 5:22
6

You can use reverseObjectEnumerator

for (id someObject in [myArray reverseObjectEnumerator])
{
    // print some info
    NSLog([someObject description]);
}

Hope this helps!

1
  • Thanks, it is still using for loop without block, but maybe this is the only other solution
    – hzxu
    Nov 9, 2012 at 3:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.