EXC_BAD_ACCESS with MKPinAnnotationView

后端 未结 2 1201
南笙
南笙 2021-01-21 09:24

I have a problem displaying my MKPinAnnotationView on the mapView in iOS. I get this error but i don\'t understand where the error comes from : \"EXC_BAD_ACCESS\". My code seems

相关标签:
2条回答
  • 2021-01-21 09:34

    You must init the annotation view using initWithAnnotation:reuseIdentifier:. For example:

    MKPinAnnotationView *pv = [[[MKPinAnnotationView alloc] 
        initWithAnnotation:annotation reuseIdentifier:@"annot"] autorelease];
    

    However, you should also take advantage of annotation view re-use by calling dequeueReusableAnnotationViewWithIdentifier first.

    Edit:
    In the docs for MKAnnotationView, the paragraph titled "Reusing Annotation Views" explains why you should use dequeueReusableAnnotationViewWithIdentifier. So the code for viewForAnnotation would look like this:

    -(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation 
    {
        static NSString *myAnnotationIdentifier = @"annot";
    
        MKPinAnnotationView *pv = (MKPinAnnotationView *)[mapView 
            dequeueReusableAnnotationViewWithIdentifier:myAnnotationIdentifier];
        if (!pv)
        {
            pv = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation 
                    reuseIdentifier:myAnnotationIdentifier] autorelease];
            [pv setPinColor:MKPinAnnotationColorGreen];
            [pv setCanShowCallout:YES];
            [pv setRightCalloutAccessoryView:[UIButton buttonWithType:UIButtonTypeDetailDisclosure]];
        }
        else
        {
            //we're re-using an annotation view
            //update annotation property in case re-used view was for another  
            pv.annotation = annotation;
        }
    
        return pv;
    }
    
    0 讨论(0)
  • 2021-01-21 09:42

    Try:

    MKPinAnnotationView *pv = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
    
    0 讨论(0)
提交回复
热议问题