I came across this piece of code in Apple's Location and Maps Programming Guide:
- (MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id <MKAnnotation>)annotation
{
// If the annotation is the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// Handle any custom annotations.
if ([annotation isKindOfClass:[MyCustomAnnotation class]])
{
// Try to dequeue an existing pin view first.
MKPinAnnotationView* pinView = (MKPinAnnotationView*)[mapView
dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];
if (!pinView)
{
// If an existing pin view was not available, create one.
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:@"CustomPinAnnotationView"];
pinView.pinColor = MKPinAnnotationColorRed;
pinView.animatesDrop = YES;
pinView.canShowCallout = YES;
// If appropriate, customize the callout by adding accessory views (code not shown).
}
else
pinView.annotation = annotation;
return pinView;
}
return nil;
}
I have a question regarding this part:
else
pinView.annotation = annotation;
I saw the same code in a Stackoverflow answer:
Unrelated, but you also need to set the view's
annotation
property when it is being re-used (in the case when it is not nil after the dequeue). So add anelse
block to theif (pinAnnotation == nil)
:else { //annotation view being re-used, set annotation to current... pinAnnotation.annotation = annotation; }
Why is the annotation property set in the else block? Shouldn't the annotation be set regardless if a view was reused or not?