更新时间:2022-12-13 21:59:07
注释$
中的c $ c>属性MKAnnotationView
通常输入为 id< MKAnnotation>
。
The annotation
property in MKAnnotationView
is typed generically as id<MKAnnotation>
.
这意味着它将指向一些实现 MKAnnotation
协议的对象。
该协议只定义了三个标准属性( title
, subtitle
, coordinate
)。
That means it will point to some object that implements the MKAnnotation
protocol.
That protocol only defines three standard properties (title
, subtitle
, and coordinate
).
您的自定义类 myAnnotation
实现 MKAnnotation
协议,因此有三个标准属性,但也有一些自定义属性。
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.
让编译器知道注释
在这种情况下,对象具体 myAnnotation
的实例,您需要将其强制转换,以便它可以让您在没有警告的情况下访问自定义属性或错误(代码完成也将开始帮助你)。
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).
在转换之前,重要的是要检查对象是否真的是你想要使用它的类型 isKindOfClass:
。如果将对象转换为实际不存在的类型,则很可能最终会在运行时生成异常。
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.
示例:
- (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);
}
}