Reputation: 8820
Im gettin the "Collection was mutates while beign enumerated" exception when my code is like this as follows:
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--;
}
}
}
Can anyone please suggest me what's the wrong in the code and how to solve the issues.
Thanks to all, Madan.
Upvotes: 2
Views: 17688
Reputation: 8759
Basically you are modifying the list in the loop you are iterating over it. The line that causes the problem is:
[mainMapView removeAnnotation:poi];
as you are iterating over mainMapView.annotations. A possible solution is to accumulate the elements you want to delete in a different list and remove them after the loop.
Based on your code, a possible solution would be:
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];
Upvotes: 11