我在设置 for 循环时偶然发现了以下快捷方式(与我一直使用的教科书示例相比的快捷方式):
for (Item *i in items){ ... }
相对于较长的格式:
for (NSInteger i = 0; i < [items count]; i++){ ... } //think that's right
如果我使用的是较短的版本,是否有办法删除当前正在迭代的项目(即“i”)?还是我需要使用更长的格式?
最佳答案
在 fast-enumerating 期间,您不能从数组中删除对象它:
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:
方法将它们从容器中移除。
关于objective-c - 从 NSMutableArray 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2757046/