*** Terminating app due to uncaught exception ‘NSGenericException‘, reason: ‘*** Collection <__NSArrayM: 0x17542520> was mutated while being enumerated.‘
从字面上不难理解,Crash的原因在于我们一边遍历数组,一边修改该数组数据。例如:
NSMutableArray *OriginalArray = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"3",@"4",nil];
for (id obj in OriginalArray){
if ([obj isEqualToString:@"3"]){
[OriginalArray removeObject:obj]
}
}
很自然我们会想到copy一个数组,在副本数组中进行遍历操作,如果符合条件我们就在原始数组中进行处理。
NSMutableArray *DuplicateArray = [OriginalArray mutableCopy];
for(id obj in DuplicateArray){
if ([ob isEqualToString:@"3"]){
[OriginalArray removeObject:obj];
}
}
时间: 2024-10-05 06:26:41