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

一个人想着一个人 提交于 2019-11-30 04:09:13

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

Mike Abdullah

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.

From here:

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

 while( anObject = [myIterator nextObject])
 {
     /* do something useful with anObject */
 }
[NsArray reverseObjectEnumerator]
for (int i = ((int)[array count] - 1); i > -1; i--) {
    NSLog(@"element: %@",array[i]);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!