cannyboy
cannyboy

Reputation: 24406

Slow down when dealing with MKAnnotations on MKMapView

I'm stepping thru the annotations on my map, in order to find one which has a certain tag. I then remove this annotation, and add a new one (a diff color)

The problem is that this takes a very, very long time. Not sure why. It's going thru 300 annotations, and it takes up to 20 seconds! How can I speed this up? It there a way to, for instance, only get the annotations which are currently visible? Or, if I have the annotation, can I tell what is its index in mapView.annotations array is, so I don't have to step thru?

for (int i =0; i < [self.mapView.annotations count]; i++) 
{
        if ([[self.mapView.annotations objectAtIndex:i] isKindOfClass:[BasicMapAnnotation class]] ) 
        { 
            BasicMapAnnotation *bmaTemp =(BasicMapAnnotation*)[self.mapView.annotations objectAtIndex:i];
            if (bmaTemp.mapTag == pinTag) {
                [self.mapView removeAnnotation:[self.mapView.annotations objectAtIndex:i]];
                self.customAnnotation = [[[BasicMapAnnotation alloc] initWithLatitude:[shop.latitude doubleValue] andLongitude:[shop.longitude doubleValue]] autorelease];
                self.customAnnotation.mapTag = pinTag;
                [self.mapView addAnnotation:self.customAnnotation];
            }

        }
}

Upvotes: 0

Views: 950

Answers (1)

fscheidl
fscheidl

Reputation: 2301

If you are sure that the Annotation you want to modify is actually visible, you could use something like

for (id annotation in [self.mapView annotationsInMapRect:self.mapView.visibleMapRect]){
    if([annotation isKindOfClass:[BasicMapAnnotation class]]){
        BasicMapAnnotation *annotationToModify = annotation;
        if (bmaTemp.mapTag == pinTag) {
            [self.mapView removeAnnotation:annotationToModify];
            self.customAnnotation = [[[BasicMapAnnotation alloc] initWithLatitude:[shop.latitude doubleValue] andLongitude:[shop.longitude doubleValue]] autorelease];
            self.customAnnotation.mapTag = pinTag;
            [self.mapView addAnnotation:self.customAnnotation];
        }
    }
}

If you want to know the index of a single given annotation:

int annotationIndex = [self.mapView.annotations indexOfObject:givenAnnotation];

Untested, I wrote this here on SO so please let me know, whether it works or not.

Upvotes: 2

Related Questions