How do I keep data associated with an MKAnnotation object after the user taps the pin, sees a callout, and taps the disclosure button which opens a detailed view controller?
In the showPinDetails:
method, you can get the currently selected annotation from the map view's selectedAnnotations
property.
That property is an NSArray
but since the map view only allows one annotation to be selected at a time, you would just use the object at index 0. For example:
- (void)showPinDetails:(id)sender
{
if (mapView.selectedAnnotations.count == 0)
{
//no annotation is currently selected
return;
}
id<MKAnnotation> selectedAnn = [mapView.selectedAnnotations objectAtIndex:0];
if ([selectedAnn isKindOfClass[VoiceMemoryAnnotation class]])
{
VoiceMemoryAnnotation *vma = (VoiceMemoryAnnotation *)selectedAnn;
NSLog(@"selected VMA = %@, blobkey=%@", vma, vma.blobkey);
}
else
{
NSLog(@"selected annotation (not a VMA) = %@", selectedAnn);
}
detailViewController = [[MemoryDetailViewController alloc]initWithNibName:@"MemoryDetailViewController" bundle:nil];
[self presentModalViewController:detailViewController animated:YES];
}
Instead of using a custom button action method, it can be easier to use the map view's calloutAccessoryControlTapped
delegate method which lets you get access to the selected annotation more directly. In viewForAnnotation
, remove the addTarget
and just implement the delegate method:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view
calloutAccessoryControlTapped:(UIControl *)control
{
id<MKAnnotation> selectedAnn = view.annotation;
if ([selectedAnn isKindOfClass[VoiceMemoryAnnotation class]])
{
VoiceMemoryAnnotation *vma = (VoiceMemoryAnnotation *)selectedAnn;
NSLog(@"selected VMA = %@, blobkey=%@", vma, vma.blobkey);
}
else
{
NSLog(@"selected annotation (not a VMA) = %@", selectedAnn);
}
//do something with the selected annotation...
}