当我的代码如下所示时,我开始了“收集是变异的,而beign枚举”异常:
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--;
}
}
}
任何人都可以告诉我代码中的错误以及如何解决问题。
感谢所有人, 马丹。
答案 0 :(得分:11)
基本上,您正在修改正在迭代它的循环中的列表。导致问题的一行是:
[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];