I have a simple array or MKAnnotations for location objects that are fetched from CoreData upon view load. When I remove a location object, I also manually remove the location object from the array. After removing from array I call removeAnnotations() and then addAnnotations() based on the array. I notice that the MKAnnotationView is no longer at the removed location, however it is not removed from the MapView only moved to 0º lat 0º lon.
I am not sure what I am doing wrong in order to get it to completely remove from the MapView.
*** Note: I am following a tutorial, and for learning processes I am manually updating the locations array instead of using NSFetchedResultsController.
Thoughts?
Here is the code:
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)
}
Your problem is that when you execute mapView.removeAnnotations(locations)
the locations
array has already been updated and the deleted annotation is no longer in that array, so it isn't removed. You can remove all current annotations by referring to the annotations
property on the MapView itself -
func drawAnnotations() {
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotations(locations)
}