我有一个简单的数组或MKAnnotations用于在视图加载时从CoreData获取的位置对象。当我删除位置对象时,我还手动从数组中删除位置对象。从数组中删除后,我调用removeAnnotations(),然后根据数组addAnnotations()。我注意到MKAnnotationView不再位于删除的位置,但是它不会从MapView中移除,只能移动到0ºlat0º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)
}
答案 0 :(得分:2)
您的问题是,当您执行mapView.removeAnnotations(locations)
时,locations
数组已更新且已删除的注释不再位于该数组中,因此不会将其删除。您可以通过引用MapView本身的annotations
属性来删除所有当前注释 -
func drawAnnotations() {
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotations(locations)
}