MKAnnotationView 未从 MKMapView 中删除

MKAnnotationView not Removing from MKMapView

我有一个简单的数组或 MKAnnotations,用于在视图加载时从 CoreData 获取的位置对象。当我删除一个位置对象时,我也手动从数组中删除了位置对象。从数组中删除后,我调用 removeAnnotations() 然后基于数组调用 addAnnotations()。我注意到 MKAnnotationView 不再位于已删除的位置,但它并未从 MapView 中删除,仅移动到 0º lat 0º lon。

我不确定为了让它从 MapView 中完全删除我做错了什么。

*** 注意:我正在学习教程,对于学习过程,我正在手动更新位置数组而不是使用 NSFetchedResultsController。

想法?

代码如下:

var managedObjectContext: NSManagedObjectContext! {
    didSet {
        NSNotificationCenter.defaultCenter().addObserverForName(NSManagedObjectContextObjectsDidChangeNotification, object: managedObjectContext, queue: NSOperationQueue.mainQueue()) { notification in
            if self.isViewLoaded() {
                if let dictionary = notification.userInfo {

                    if dictionary["inserted"] != nil {

                        print("*** Inserted")
                        let insertedLocationSet: NSSet = dictionary["inserted"] as! NSSet
                        let insertedLocationArray: NSArray = insertedLocationSet.allObjects
                        let insertedLocation = insertedLocationArray[0] as! Location
                        self.locations.append(insertedLocation)

                    } else if dictionary["deleted"] != nil {

                        print("*** Deleted")
                        let deletedLocationSet = dictionary["deleted"] as! NSSet
                        let deletedLocationArray = deletedLocationSet.allObjects
                        let deletedLocation = deletedLocationArray[0] as! Location

                        if let objectIndexInLocations = self.locations.indexOf(deletedLocation) {

                            self.locations.removeAtIndex(objectIndexInLocations)

                        }

                    }
                }
            }

            self.drawAnnotations()

        }
    }
}

var locations = [Location]()


func updateLocations() {  // called by viewDidLoad()

    let entity = NSEntityDescription.entityForName("Location", inManagedObjectContext: managedObjectContext)

    let fetchRequest = NSFetchRequest()
    fetchRequest.entity = entity

    locations = try! managedObjectContext.executeFetchRequest(fetchRequest) as! [Location]

    drawAnnotations()

}

func drawAnnotations() {

    mapView.removeAnnotations(locations)
    mapView.addAnnotations(locations)

}

你的问题是,当你执行 mapView.removeAnnotations(locations) 时,locations 数组已经更新,删除的注释不再在该数组中,因此它不会被删除。您可以通过引用 MapView 本身上的 annotations 属性 来删除所有当前注释 -

func drawAnnotations() {
    mapView.removeAnnotations(mapView.annotations)
    mapView.addAnnotations(locations) 
}