How to access to an annotation attribute inside method calloutAccessoryControlTapped

穿精又带淫゛_ 提交于 2019-11-29 12:46:40

The annotation property in MKAnnotationView is typed generically as id<MKAnnotation>.

That means it will point to some object that implements the MKAnnotation protocol.
That protocol only defines three standard properties (title, subtitle, and coordinate).

Your custom class myAnnotation implements the MKAnnotation protocol and so has the three standard properties but also some custom ones.

Because the annotation property is typed generically, the compiler only knows about the three standard properties and gives warnings or errors if you try to access custom properties that are not in the standard protocol.

To let the compiler know that the annotation object in this case is specifically an instance of myAnnotation, you need to cast it so that it will let you access the custom properties without warnings or errors (and the code completion will also start helping you).

Before casting, it's important to check that the object really is of the type you want to cast it to using isKindOfClass:. If you cast an object to a type that it really isn't, you'll most likely end up generating exceptions at run-time.

Example:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{   
    if ([view.annotation isKindOfClass:[myAnnotation class]])
    {
        myAnnotation *ann = (myAnnotation *)view.annotation;
        NSLog(@"ann.title = %@, ann.idEmpresa = %d", ann.title, ann.idEmpresa);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!