当我的代码如下所示时,我遇到“集合在枚举时发生变化”异常:
NSString *poiStr = nil;
int SuccessValue=0;
NSMutableArray* poisArray=[[NSMutableArray alloc]init];
for (id<MKAnnotation> annotation in mainMapView.annotations)
{
MKAnnotationView* anView = [mainMapView viewForAnnotation: annotation];
if(anView)
{
POI* locationPOI = (POI*)[anView annotation];
printf("\n Location poi shape groupId:%s=====%s",[locationPOI.shapeSpaceGroupId UTF8String],[poiStr UTF8String]);
if((poiStr == nil) || ([poiStr isEqualToString:locationPOI.shapeSpaceGroupId]))
{
poiStr = locationPOI.shapeSpaceGroupId;
[poisArray addObject:locationPOI];
SuccessValue++;
}
printf("\n successValue:%d",SuccessValue);
if(SuccessValue==2)
{
POI* poi=[poisArray objectAtIndex:0];
[mainMapView removeAnnotation:poi];
SuccessValue--;
}
}
}
任何人都可以建议我代码中有什么问题以及如何解决问题。
谢谢大家, 马丹。
最佳答案
基本上,您正在迭代列表的循环中修改列表。导致问题的行是:
[mainMapView removeAnnotation:poi];
当您迭代 mainMapView.annotations 时。一种可能的解决方案是将要删除的元素累积在不同的列表中,并在循环后将其删除。
根据您的代码,可能的解决方案是:
NSString *poiStr = nil;
int SuccessValue=0;
NSMutableArray* poisArray=[[NSMutableArray alloc]init];
NSMutableArray *to_delete = [[NSMutableArray alloc] init];
for (id<MKAnnotation> annotation in mainMapView.annotations)
{
MKAnnotationView* anView = [mainMapView viewForAnnotation: annotation];
if(anView)
{
POI* locationPOI = (POI*)[anView annotation];
printf("\n Location poi shape groupId:%s=====%s",[locationPOI.shapeSpaceGroupId UTF8String],[poiStr UTF8String]);
if((poiStr == nil) || ([poiStr isEqualToString:locationPOI.shapeSpaceGroupId]))
{
poiStr = locationPOI.shapeSpaceGroupId;
[poisArray addObject:locationPOI];
SuccessValue++;
}
printf("\n successValue:%d",SuccessValue);
if(SuccessValue==2)
{
POI* poi=[poisArray objectAtIndex:0];
//[mainMapView removeAnnotation:poi];
[to_delete addObject:poi];
SuccessValue--;
}
}
}
for (id<MKAnnotation> annotation in to_delete)
[mainMapView removeAnnotation:poi];
[to_delete release];
关于iphone - 由于未捕获的异常 'NSGenericException' 而终止应用程序,原因 : '*** Collection <__NSArrayM: 0x117540> was mutated while being enumerated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4732991/