How to recognize which pin was tapped

In the showDetails: method, you can get the pin tapped from the map view’s selectedAnnotations array. Even though the property is an NSArray, just get the first item in the array since the map view only allows one pin to be selected at a time:

//To be safe, may want to check that array has at least one item first.

id<MKAnnotation> ann = [[mapView selectedAnnotations] objectAtIndex:0];

// OR if you have custom annotation class with other properties...
// (in this case may also want to check class of object first)

YourAnnotationClass *ann = [[mapView selectedAnnotations] objectAtIndex:0];

NSLog(@"ann.title = %@", ann.title);

By the way, instead of doing addTarget and implementing a custom method, you can use the map view’s calloutAccessoryControlTapped delegate method. The annotation tapped is available in the view parameter:

-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view 
    calloutAccessoryControlTapped:(UIControl *)control
{
    NSLog(@"ann.title = %@", view.annotation.title);
}

Make sure you remove the addTarget from viewForAnnotation if you use calloutAccessoryControlTapped.

Leave a Comment