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, 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]]; 
    } 
}

Answers


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]];  
    }  
}

Need Your Help

Ensuring random order for iteration over Set Python

python set iteration

I am iterating over a Set in Python. In my application I prefer that the iteration be in a random order each time. However what I see is that I get the same order each time I run the program. This ...

How to style a custom Silverlight 4 UserControl?

silverlight user-controls custom-controls

I have a custom UserControl that I created as a navigation menu that parses an xml file and populates itself with hyperlink buttons. So basically my control is an empty stackpanel, and when it's lo...