【问题标题】:Error: Could not cast value of type NSKVONotifying_MKUserLocation to Park_View.AttractionAnnotation错误:无法将 NSKVONotifying_MKUserLocation 类型的值转换为 Park_View.AttractionAnnotation
【发布时间】:2015-09-13 04:59:58
【问题描述】:
当使用这个函数时:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let annotationView = AttractionAnnotationView(annotation: annotation, reuseIdentifier: "Attraction")
annotationView.canShowCallout = true
return annotationView
}
发生了这个错误:
无法将“NSKVONotifying_MKUserLocation”(0x7e8a62b0) 类型的值转换为“Park_View.AttractionAnnotation”(0xf7948)。
它运行良好,但是当我尝试将 CoreLocation 添加到我的代码中以查找用户位置时,我开始出现此错误。
【问题讨论】:
标签:
swift
mapkit
core-location
mkannotation
【解决方案1】:
函数AttractionAnnotationView 可能返回MKUserLocation 对象而不是AttractionAnnotation 对象。
【解决方案2】:
我发现 MKUserLocation 也是一个注解。
这是我提出的解决方案,它解决了错误。
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if (annotation is MKUserLocation) {
return nil
}
else {
let annotationView = AttractionAnnotationView(annotation: annotation, reuseIdentifier: "Attraction")
annotationView.canShowCallout = true
return annotationView
}
}
【解决方案3】:
您的 AttractionAnnotation 类中有自定义覆盖的 isEqual() 函数吗?如果是这样,请在比较之前检查它是否没有将比较对象(函数参数)转换为 AttractionAnnotation。
【解决方案4】:
当您单击/点击用户位置时,Xcode 10.2 中也会发生同样的事情......所以试试这样的事情:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if (view.annotation is MKUserLocation) {
return
}
...
}