Is there an easy way to iterate over an NSArray backwards?

Objective CNsarray

Objective C Problem Overview


I've got an NSArray and have to iterate over it in a special case backwards, so that I first look at the last element. It's for performance reasons: If the last one just makes no sense, all previous ones can be ignored. So I'd like to break the loop. But that won't work if I iterate forward from 0 to n. I need to go from n to 0. Maybe there is a method or function I don't know about, so I wouldn't have to re-invent the wheel here.

Objective C Solutions


Solution 1 - Objective C

To add on the other answers, you can use -[NSArray reverseObjectEnumerator] in combination with the fast enumeration feature in Objective-C 2.0 (available in Leopard, iPhone):

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

Source with some more info: http://cocoawithlove.com/2008/05/fast-enumeration-clarifications.html

Solution 2 - Objective C

Since this is for performace, you have a number of options and would be well advised to try them all to see which works best.

  • [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:…]
  • -[NSArray reverseObjectEnumerator]
  • Create a reverse copy of the array and then iterate through that normally
  • Use a standard C for loop and start and work backwards through the array.

More extreme methods (if performance is super-critical)

  • Read up on how Cocoa implements fast object enumeration and create your own equivalent in reverse.
  • Use a C or C++ array.

There may be others. In which case, anyone feel free to add it.

Solution 3 - Objective C

From here:

 NSEnumerator* myIterator = [myArray reverseObjectEnumerator];
 id anObject;

 while( anObject = [myIterator nextObject])
 {
     /* do something useful with anObject */
 }

Solution 4 - Objective C

[NsArray reverseObjectEnumerator]

Solution 5 - Objective C

for (int i = ((int)[array count] - 1); i > -1; i--) {
    NSLog(@"element: %@",array[i]);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThanksView Question on Stackoverflow
Solution 1 - Objective CSijmen MulderView Answer on Stackoverflow
Solution 2 - Objective CMike AbdullahView Answer on Stackoverflow
Solution 3 - Objective CNaaffView Answer on Stackoverflow
Solution 4 - Objective CCiNNView Answer on Stackoverflow
Solution 5 - Objective CVyacheslav ZubenkoView Answer on Stackoverflow