iOS 11中MKMapView集群的性能不佳

Jav*_*cio 12 mapkit ios swift

我一直在使用第三方库来处理标记聚类.由于iOS 11有自己的实现,我决定继续代表"本机"实现移除第三方库.

我已经从WWDC 2017下载了示例应用程序,并按照相同的步骤操作,因此:

  • 连接MKMapView插座
  • MKAnnotation为我的模型实现协议
  • 创建一个MKMarkerAnnotationViewfor marker的视图
  • 创建一个MKMarkerAnnotationViewfor cluster的视图
  • 使用register(_:forAnnotationViewWithReuseIdentifier:)函数在mapView引用上注册两个注释
  • 添加注释到我的地图

但是,在使用第三方库时,一切都很好,使用这种方法,当我平移我的mapView并更改区域时,我的性能非常差.CPU使用率提升高达90%,而内存似乎保持稳定,我感觉延迟移动,有时甚至是应用程序崩溃.我正在加载大约600个注释.

有什么建议吗?

这是代码:

class MapViewClusteringViewController: UIViewController, MKMapViewDelegate {

  @IBOutlet weak var mapView: MKMapView!
  private var databaseService: LocalDataService!

  override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self
    mapView.register(StopMarker.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
    mapView.register(StopCluster.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)

    databaseService.fetchMarkers { markers in
      mapView.addAnnotation(markers)
    }
  }
}

class StopMarker: MKMarkerAnnotationView {
  override var annotation: MKAnnotation? {
    willSet {
      clusteringIdentifier = "busStopCluster"
      subtitleVisibility = .adaptive
      markerTintColor = .red
    }
  }
}

class StopCluster: MKMarkerAnnotationView {
  override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
    super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
    displayPriority = .defaultHigh
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  override var annotation: MKAnnotation? {
    willSet {
      if let cluster = newValue as? MKClusterAnnotation {
        markerTintColor = .green
        glyphText = "\(cluster.memberAnnotations.count)"
      }
    }
  }
}

class StopAnnotation: NSObject, MKAnnotation {
  var coordinate: CLLocationCoordinate2D
  var title: String?

  init(coordinate: CLLocationCoordinate2D, title: String) {
    self.coordinate = coordinate
    self.title = title
  }
}
Run Code Online (Sandbox Code Playgroud)

A S*_*ANI 3

这里,您可以阅读:

不要自己创建此类的实例。当两个或多个注释视图在地图表面上组合得太紧密时,MapKit 会自动创建集群注释。

您可以尝试不自己创建此类的实例。