可能重複的所有對象:
Best way to remove from NSMutableArray while iterating?刪除從一個NSMutableArray匹配條件
MODS的:我意識到這是的this question重複,你可以關閉/刪除呢?
可能重複的所有對象:
Best way to remove from NSMutableArray while iterating?刪除從一個NSMutableArray匹配條件
MODS的:我意識到這是的this question重複,你可以關閉/刪除呢?
如果你不希望創建一個臨時的或新的數組,你可以這樣做:
NSMutableArray *array = ...; // your mutable array
NSIndexSet *toBeRemoved = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
// The block is called for each object in the array.
BOOL removeIt = ...; // YES if the element should be removed and NO otherwise
return removeIt;
}];
[array removeObjectsAtIndexes:toBeRemoved];
(但是使用臨時的NSIndexSet
。)
備註:我的想法是,如Richard J. Ross III所建議的,在迭代過程中刪除所有匹配元素可能會更有效,而不是單獨刪除每個元素。
但一個簡短的測試表明,情況並非如此。使用1000000個元素從數組中移除每個第二個元素幾乎與我的計算機上的兩種方法相同。
您可以在迭代時刪除對象。 –
@ RichardJ.RossIII:當我嘗試這樣做時,它崩潰:'***由於未捕獲的異常'NSGenericException'而終止應用程序,原因:'*** Collection <__ NSArrayM:0x6baab80>在枚舉時發生了變化.'' –
只是迭代它的舊式。使用索引的整數。 –