views:

157

answers:

2

I've got this code to erase an annotations (pins) in my mkmapview without erasing my blue dot (userLocation). The problem is that it erasing the pins I've added in seemingly random numbers. when it's called through an IBAction it removes the first 5 then click again it removes the next 3, then the next 2, then the last one.

When pressed I need it to remove that latest pin...etc. etc.

for (int i = 0; 
     i < [mapView.annotations count]; 
     i++

     )



{ if ([[mapView.annotations objectAtIndex:i] isKindOfClass:[MyAnnotation class]])
    { 
[mapView removeAnnotation:[mapView.annotations objectAtIndex:i]]; 
    } 
}
+1  A: 

The problem is that you are modifying the annotation collection while iterating over it. At every execution of the loop, the loop's termination condition [mapView.annotations count] changes its value. This will lead to unforeseen behavior. You should

  • either put all annotations you want to remove into an empty mutable array inside the loop an then call removeAnnotations: with this array as a parameter after you exit the loop,
  • or count down from the annotation with the highest index to 0.
Ole Begemann
Following Ole Begermann's advice, this works for (int i = [mapView.annotations count]-1; i >= 0 ; i--) { [mapView removeAnnotation:[mapView.annotations objectAtIndex:i]]; }
Oh Danny Boy
A: 

Use this code NSInteger *counter = [mapView.annotations count];

for (int i = 0; i < counter; i++ )

{

if ([[mapView.annotations objectAtIndex:i] isKindOfClass:[MyAnnotation class]])

{  

[mapView removeAnnotation:[mapView.annotations objectAtIndex:i]];

}  

}

Amarpreet