2013-04-01 31 views
2

此代碼運行時沒有崩潰,我沒有在文檔中看到任何內容,但是它確實安全嗎?在enumerateObjectsUsingBlock:?期間使用removeObject安全嗎?

[mutableArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    // do some stuff to obj before removing it 
    [mutableArray removeObject:obj]; 
}]; 
+0

這裏有一些有用的答案:[集合在被列舉的目標C錯誤時發生了變化](http://stackoverflow.com/questions/14457369/collection-was-mutated-while-being-enumerated-error-in-jective -c) – Monolo

回答

5

我覺得這不應該做

在枚舉中,該對象被視爲const。

我嘗試相同的代碼,我收到以下錯誤:

Collection <__NSArrayM: 0x10053b8d0> was mutated while being enumerated. 

驗證碼:

NSMutableArray *mutableArray=[NSMutableArray new]; 
[mutableArray addObject:@"A"]; 
[mutableArray addObject:@"Ab"]; 
[mutableArray addObject:@"Ac"]; 
[mutableArray addObject:@"Ad"]; 

[mutableArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    // do some stuff to obj before removing it 
    [mutableArray removeObject:obj]; 
    NSLog(@"--->%@",mutableArray); 
}]; 
+0

即使在發佈這個答案後,我想知道它錯誤地說'NSArrayM是mutatated'它是'M'不是'I'。所以爲什麼不能mutableArray被突變。 –

+1

因爲在枚舉過程中集合不能被突變(請參閱「重複問題」的答案)。集合是否可變是無關緊要的。 –

4

這是你永遠不應該做的事情。相反,將所有元素索引收集到一個NSMutableIndexSet對象中,然後再使用removeObjectsAtIndexes:一次刪除所有對象。