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!

hzxu
  • 5,753
  • 11
  • 60
  • 95

2 Answers2

19

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

rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • 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 09 '12 at 04: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 09 '12 at 05:22
6

You can use reverseObjectEnumerator

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

Hope this helps!

Eric
  • 5,671
  • 5
  • 31
  • 42
  • Thanks, it is still using for loop without block, but maybe this is the only other solution – hzxu Nov 09 '12 at 03:24