2

I have a MKMapView annotation object that has a right callout accessory detail disclosure button. When the button is pressed I am using addTarget:action:forControlEvent to call a selector method which creates a detail viewController and pushes it onto the view stack.

My question is what is the best way to access the information on the annotation that initiated the callout detail controller. The detail disclosure button is set to call:

[button addTarget:self action:@selector(disclosurePressed:) forControlEvents:UIControlEventTouchUpInside];

Which looks like this:

- (void)disclosurePressed:(id)sender {
}

I guess I could look for the parent annotation of the sender UIButton, can anyone give me any pointers to how this is best done.

nevan king
  • 112,709
  • 45
  • 203
  • 241
fuzzygoat
  • 26,573
  • 48
  • 165
  • 294

2 Answers2

4

You might have an easier time using the MKMapViewDelegate mapView:annotationView:calloutAccessoryControlTapped: method, which tells you directly which annotation view was tapped.

nevan king
  • 112,709
  • 45
  • 203
  • 241
3

A reliable way (if you must use a custom method) is to look at the map view's selectedAnnotations property.

Though the property is an NSArray, since the map view only allows one annotation to be selected at a time, the one that the user just tapped will be at index 0 so it would be:

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

//Here, you can cast annTapped to a custom annotation class if needed.
//Be sure to check what kind of class it is first.

You may also want to first check that mapView.selectedAnnotations.count is not zero just to be safe.


However, a better way (as nevan king already answered) than using addTarget and a custom action method is to use the map view's calloutAccessoryControlTapped delegate method where the annotation is directly accessible through the view parameter using:

id<MKAnnotation> annTapped = view.annotation;
  • How can i get a number out of this? e.g if i want to get the ID# of the annotation to retrieve the appropriate content from an API etc – carbonr Mar 29 '12 at 08:05
  • @carbonr, Hope that clears it up. If still confused, suggest you [Ask A Question](http://stackoverflow.com/questions/ask) and include details of the problem. –  Mar 29 '12 at 12:39
  • Anna you are awesome! The previous links was the solution. What had happened was it threw an error when i was storing data in my custom class so i thought i was wrong, but i have figured it out – carbonr Mar 29 '12 at 12:55