objective-c 有没有一种简单的方法可以向后迭代 NSArray?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/844189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there an easy way to iterate over an NSArray backwards?
提问by Thanks
I've got an NSArrayand 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.
我有一个NSArray并且必须在特殊情况下向后迭代它,以便我首先查看最后一个元素。这是出于性能原因:如果最后一个没有意义,则可以忽略所有先前的。所以我想打破循环。但是,如果我从 0 向前迭代到 n,那将不起作用。我需要从 n 到 0。也许有一个我不知道的方法或函数,所以我不必在这里重新发明轮子。
回答by Sijmen Mulder
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):
要添加其他答案,您可以-[NSArray reverseObjectEnumerator]结合 Objective-C 2.0 中的快速枚举功能(在 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
更多信息来源:http: //cocoawithlove.com/2008/05/fast-enumeration-clarifications.html
回答by 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 arrayand then iterate through that normally
- Use a standard C for loop and start and work backwards through the array.
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:…]-[NSArray reverseObjectEnumerator]- 创建数组的反向副本,然后正常迭代
- 使用标准的 C for 循环并开始并通过数组向后工作。
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.
- 阅读 Cocoa 如何实现快速对象枚举并反向创建您自己的等效项。
- 使用 C 或 C++ 数组。
There may be others. In which case, anyone feel free to add it.
可能还有其他人。在这种情况下,任何人都可以随意添加它。
回答by Naaff
回答by CiNN
[NsArray reverseObjectEnumerator]
回答by Vyacheslav Zubenko
for (int i = ((int)[array count] - 1); i > -1; i--) {
NSLog(@"element: %@",array[i]);
}

