需求是遍歷一個(gè)存 model 的數(shù)組 如果 id相同就刪除
我寫的是
for (UserModel*model in self.userArray) {
if (model.uId == deleteId) {
[self.userArray removeObject:model];
}
}
然后崩潰了。。。原因是Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘*** Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.’在枚舉的時(shí)候發(fā)生了變化
然后在網(wǎng)上查到 是因?yàn)樾薷牧吮闅v對(duì)象 所以導(dǎo)致崩潰
然后我就想到辦法
BOOL isContain = NO;
for (UserModel *model in self.userArray) {
if (model.uId == deleteId) {
isContain = YES;
}
}
if (isContain) {
[self.userArray removeObject:model];
}
然后在網(wǎng)上找到其他辦法
一、
定義一個(gè)臨時(shí)數(shù)組 = self.userArray
然后遍歷臨時(shí)數(shù)組,但是操作self.userArray;
二、
利用block
NSMutableArray *tempArray = [[NSMutableArray alloc]initWithObjects:@"12",@"23",@"34",@"45",@"56", nil];
[tempArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isEqualToString:@"34"]) {
*stop = YES;
if (*stop == YES) {
[tempArray replaceObjectAtIndex:idx withObject:@"3333333"];
}
}
if (*stop) {
NSLog(@"array is %@",tempArray);
}
}];
此方法的好處是 這個(gè)便利方法 比for 遍歷更快, 因?yàn)榇朔椒ㄕ业椒系臈l件后就會(huì)停止遍歷 然后修改數(shù)組。