Trying the exercise in MyLocations, to use NSNotification object to help make a more efficient way of reloading locations after any changes. Here’s the code after looking at others’ ideas, but no solutions. I don’t get any errors, but when I add a location it never appears on the map, and when I delete a location it doesn’t disappear. In fact, it appears to leave an item in the data store which has no name or description and a lat/lon 0f 0.00000/0.00000. If I stop the app and restart, then the pins disappear. Self.updateLocations is commented out since that would seem to defeat the purpose of the exercise.
var managedObjectContext: NSManagedObjectContext! {
didSet {
NSNotificationCenter.defaultCenter().addObserverForName(NSManagedObjectContextObjectsDidChangeNotification, object: managedObjectContext, queue: NSOperationQueue.mainQueue()) { notification in
if self.isViewLoaded() {
// self.updateLocations()
if let dictionary = notification.userInfo {
print(dictionary["inserted"])
print(dictionary["deleted"])
print(dictionary["updated"])
if let locations = dictionary["inserted"] as? Set<Location> {
for location in locations {
self.mapView.addAnnotation(location)
}
if let locations = dictionary["deleted"] as? Set<Location> {
for location in locations {
self.mapView.removeAnnotation(location)
}
}
if let locations = dictionary["updated"] as? Set<Location> {
for location in locations {
self.mapView.removeAnnotation(location)
self.mapView.addAnnotation(location)
}
}
}
}
}
}
}