在 Cocoa 中,如果我想遍历 NSMutableArray 并删除符合特定条件的多个对象,那么在每次删除对象时无需重新启动循环的最佳方法是什么?
In Cocoa, if I want to loop through an NSMutableArray and remove multiple objects that fit a certain criteria, what's the best way to do this without restarting the loop each time I remove an object?
谢谢,
只是为了澄清 - 我正在寻找最好的方法,例如比手动更新我所在的索引更优雅的东西.例如在 C++ 中我可以做到;
Just to clarify - I was looking for the best way, e.g. something more elegant than manually updating the index I'm at. For example in C++ I can do;
iterator it = someList.begin(); while (it != someList.end()) { if (shouldRemove(it)) it = someList.erase(it); } 推荐答案为了清楚起见,我喜欢制作一个初始循环,在那里我收集要删除的项目.然后我删除它们.下面是一个使用 Objective-C 2.0 语法的示例:
For clarity I like to make an initial loop where I collect the items to delete. Then I delete them. Here's a sample using Objective-C 2.0 syntax:
NSMutableArray *discardedItems = [NSMutableArray array]; for (SomeObjectClass *item in originalArrayOfItems) { if ([item shouldBeDiscarded]) [discardedItems addObject:item]; } [originalArrayOfItems removeObjectsInArray:discardedItems];那么关于指数是否正确更新或其他小记账细节就没有问题了.
Then there is no question about whether indices are being updated correctly, or other little bookkeeping details.
编辑添加:
在其他答案中已经指出逆公式应该更快.即如果您遍历数组并组成一个新的对象数组来保留,而不是要丢弃的对象.这可能是正确的(尽管分配新数组和丢弃旧数组的内存和处理成本如何?)但即使它更快,它也可能不像天真的实现那么大,因为 NSArrays不要表现得像普通"数组.他们谈论话题,但他们走的路不同.在这里看到一个很好的分析:
It's been noted in other answers that the inverse formulation should be faster. i.e. If you iterate through the array and compose a new array of objects to keep, instead of objects to discard. That may be true (although what about the memory and processing cost of allocating a new array, and discarding the old one?) but even if it's faster it may not be as big a deal as it would be for a naive implementation, because NSArrays do not behave like "normal" arrays. They talk the talk but they walk a different walk. See a good analysis here:
逆公式可能更快,但我从来不需要关心它是否更快,因为上面的公式总是足够快满足我的需要.
The inverse formulation may be faster, but I've never needed to care whether it is, because the above formulation has always been fast enough for my needs.
对我来说,最重要的信息是使用您最清楚的任何公式.仅在必要时进行优化.我个人认为上面的公式最清楚,这就是我使用它的原因.但如果逆公式对你来说更清楚,那就去做吧.
For me the take-home message is to use whatever formulation is clearest to you. Optimize only if necessary. I personally find the above formulation clearest, which is why I use it. But if the inverse formulation is clearer to you, go for it.
更多推荐
迭代时从 NSMutableArray 中删除的最佳方法?
发布评论