从 NSMutableArray 中删除对象 [英] Removing object from NSMutableArray
问题描述
我在设置 for 循环时偶然发现了以下快捷方式(与我一直使用的教科书示例相比的快捷方式):
I stumbled across the following shortcut in setting up a for loop (shortcut compared to the textbook examples I have been using):
for (Item *i in items){ ... }
与较长的格式相反:
for (NSInteger i = 0; i < [items count]; i++){ ... } //think that's right
如果我使用较短的版本,有没有办法删除当前正在迭代的项目(即i")?还是我需要使用更长的格式?
If I'm using the shorter version, is there a way to remove the item currently being iterated over (ie 'i')? Or do I need to use the longer format?
推荐答案
快速枚举它:
枚举是安全的"——枚举器有一个突变守卫,所以如果你尝试修改集合在枚举期间,一个例外是提升.
numeration is "safe"—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration, an exception is raised.
无论如何,您为什么需要在枚举容器时更改容器?考虑存储需要删除的元素,并使用 removeObjectsInArray:
或 removeObjectsAtIndexes:
方法将它们从容器中删除.
Anyway why do you need to change you container while enumerating it? Consider storing elements that need to be deleted and remove them from your container using removeObjectsInArray:
or removeObjectsAtIndexes:
method.
这篇关于从 NSMutableArray 中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!