【问题标题】:MKAnnotationView not Removing from MKMapViewMKAnnotationView 未从 MKMapView 中移除
【发布时间】:2015-12-09 21:20:11
【问题描述】:

我有一个简单的数组或 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)

}

【问题讨论】:

  • 你能展示drawAnnotations()方法吗?您是否在代码中的任何位置调用地图视图上的removeAnnotation(:) 方法?

标签: ios swift mkmapview mkannotationview


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2014-07-02
    相关资源
    最近更新 更多