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);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…