我可以移除在循環中沒有副作用的Objective-C for
循環的項目嗎?刪除for循環中的項目沒有副作用?
例如,這可以嗎?
for (id item in items) {
if ([item customCheck]) {
[items removeObject:item]; // Is this ok here?
}
我可以移除在循環中沒有副作用的Objective-C for
循環的項目嗎?刪除for循環中的項目沒有副作用?
例如,這可以嗎?
for (id item in items) {
if ([item customCheck]) {
[items removeObject:item]; // Is this ok here?
}
沒有,因此當你發生變異的陣列,同時在快速列舉的for循環得到一個錯誤。製作數組的副本,對其進行迭代,然後從原始數據中刪除。
NSArray *itemsCopy = [items copy];
for (id item in itemsCopy) {
if ([item customCheck])
[items removeObject:item]; // Is this ok here
}
[itemsCopy release];
枚舉是「安全的」誠枚舉具有突變後衛,這樣,如果你試圖枚舉過程中修改集合,則會引發異常情況。
選項改變要枚舉通過Using Enumerators給出一個數組:要麼複製數組和枚舉通過,或建立你的循環後使用索引集。
謝謝 - McCygnus的建議似乎堅持這一點,所以它看起來不錯 – Greg 2011-04-28 23:49:53
您可以刪除這樣的:
//Create array
NSMutableArray* myArray = [[NSMutableArray alloc] init];
//Add some elements
for (int i = 0; i < 10; i++) {
[myArray addObject:[NSString stringWithFormat:@"i = %i", i]];
}
//Remove some elements =}
for (int i = (int)myArray.count - 1; i >= 0 ; i--) {
if(YES){
[myArray removeObjectAtIndex:i];
}
}
i--使差異。 ;) – user3761851 2015-05-15 14:21:48
這是不是跳過1元,因爲每個數組元素得到由1刪除時發生移位。 – 2014-02-10 11:53:13
不,我們不會使用此示例中的索引從顯示中刪除項目。 NSMutableArray的removeObject:方法會查看數組,並將第一個引用移除到找到的對象。調用內部使用indexOfObject:和removeObjectAtIndex:來完成它。如果你有足夠大的陣列,這可能是性能問題。您可以通過跟蹤索引來優化它,但是您必須對其進行調整才能刪除。 – McCygnus 2014-02-10 19:30:43