0

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 an else block to the if (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?

Community
  • 1
  • 1
Kymer
  • 1,184
  • 8
  • 20

1 Answers1

0

You initialise the MKPinAnnotationView with the annotation so the else is just so you won't set it twice. It is perfectly fine to set it twice but of course inefficient.

Erik Johansson
  • 1,188
  • 1
  • 8
  • 22