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

前端 未结 5 1626
半阙折子戏
半阙折子戏 2020-12-29 01:57

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 la

相关标签:
5条回答
  • 2020-12-29 02:24

    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.

    0 讨论(0)
  • 2020-12-29 02:33

    From here:

     NSEnumerator* myIterator = [myArray reverseObjectEnumerator];
     id anObject;
    
     while( anObject = [myIterator nextObject])
     {
         /* do something useful with anObject */
     }
    
    0 讨论(0)
  • 2020-12-29 02:37
    for (int i = ((int)[array count] - 1); i > -1; i--) {
        NSLog(@"element: %@",array[i]);
    }
    
    0 讨论(0)
  • 2020-12-29 02:45

    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

    0 讨论(0)
  • 2020-12-29 02:48
    [NsArray reverseObjectEnumerator]
    
    0 讨论(0)
提交回复
热议问题