首页 > 解决方案 > Swift Mapkit 移除注解并释放内存

问题描述

我正在使用 mapView.removeAnnotations(mapView.annotations) 删除注释,但我可以从 Xcode 中的调试中看到每个注释的内存没有释放,这最终导致我的应用程序崩溃。有没有办法释放它?我看过 ARC 和 deinit 和 weak 但我看不出这与我的代码有什么关系。

import Foundation
import MapKit

class StationMarkerView: MKMarkerAnnotationView {
  override var annotation: MKAnnotation? {
    willSet {
        
      guard let station = newValue as? Station else {
        return
      }
      canShowCallout = true

        let mapsButton = FavouriteButton()
        let  bool = station.is_favourite
        let image = bool! ? "star.fill": "star"
        
        mapsButton.setBackgroundImage(UIImage(systemName: image), for: .normal)
        
        rightCalloutAccessoryView = mapsButton
        
      markerTintColor = station.markerTintColor
      glyphImage = station.glyphImage
      
    }
  }
}

我曾尝试对“mapButton”使用弱,但 Xcode 给了我一个解除分配警告。

感谢任何帮助表示赞赏。

标签: swiftannotationsmapkitautomatic-ref-countingweak-references

解决方案


我找到了一个快速而肮脏的解决方案来解决我的问题。删除注释然后更改地图类型似乎会释放与地图视图相关的所有内存。

所以要刷新我的地图,我会...

mapView.removeAnnotations(mapView.annotations)
        
mapView.mapType = MKMapType.satellite
        
velibManager.fetchVelib()
        
mapView.mapType = MKMapType.standard

推荐阅读