移动地图时,MKMapView
会调用下面的委托功能。由于我们的应用程序的性质,我们在一个单独的线程中添加新的车辆到地图。我们注意到,执行此代码时应用程序可能会崩溃。错误发生在for循环的第5行。任何人都可以解释为什么循环返回零注释?
func regionDidChange(mapView: MKMapView, animated: Bool) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
var vehiclesToAdd = [VehicleAnnotation]()
for (var i = 0; i < self.mapView.annotations.count; i++) {
if (self.mapView.annotations[i].isKindOfClass(VehicleAnnotation)) {
let vehicleAnnotation: VehicleAnnotation! = self.mapView.annotations[i] as VehicleAnnotation
if (!MKMapRectContainsPoint(mapView.visibleMapRect, MKMapPointForCoordinate(vehicleAnnotation.coordinate))) {
vehiclesToAdd.append(vehicleAnnotation)
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.mapView.addAnnotations(vehiclesToAdd)
}
})
}
为什么会发生这种情况?