iosannotationsmkmapviewmkannotationviewmkmapviewdelegate

mapView:didDeselectAnnotationView: delegate method getting called before the annotation view is actually deselected


I am working with a map view populated with custom pins. When the user taps somewhere on the map to deselect a pin, I want to implement the map such that the pin does not become deselected (i.e. users are not able to deselect pins without selecting other pins, so at least one pin will always be selected). Here is my implementation of the didDeselectAnnotationView method:

-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    [mapView selectAnnotation:view.annotation animated:NO];
}

Essentially, I'm trying to reselect the annotation. However, after some debugging and printing to console, I realized that the annotation view isn't actually being deselected until after the method didDeselectAnnotationView: finishes running (that is, the order of events goes: user taps somewhere on map, didDeselectAnnotationView: is called and finishes executing, the annotation view is actually deselected). Has anyone else experienced this problem, or does anyone know another way to enforce the behavior for the map such that users are unable to deselect pins without selecting other pins, so that one pin will always be selected?

Thanks for the help.


Solution

  • Try deferring the re-select until after didDeselectAnnotationView is finished:

    -(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
    {
        [self performSelector:@selector(reSelectAnnotationIfNoneSelected:) 
                withObject:view.annotation afterDelay:0];
    }
    
    - (void)reSelectAnnotationIfNoneSelected:(id<MKAnnotation>)annotation
    {
        if (mapView.selectedAnnotations.count == 0)
            [mapView selectAnnotation:annotation animated:NO];
    }