remove Annotation removes random amount of annotations at a time
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, t开发者_高级运维hen 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]];
}
}
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.
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]];
}
}
精彩评论