0
您好我保存我的數據使用與AppDelegate模板生成的saveContext()。我的應用在後臺模式下記錄一組位置,然後當應用進入前臺時,我將這些位置存儲在覈心數據中。一切都被保存,它存儲,但是當我去我的視圖控制器顯示它們時,它不會顯示,除非我重新啓動應用程序並返回到它。CoreData只在重新啓動應用程序後更新?
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
if self.myLocations.count > 0 {
let context = persistentContainer.viewContext
let logEntity = NSEntityDescription.insertNewObject(forEntityName: "PostureLog", into: context)
logEntity.setValue(self.errors, forKey: "logError")
// populate log
logEntity.setValue(Date(), forKey: "logDate")
for i in 0...myLocations.count - 1 {
let locationEntity = NSEntityDescription.insertNewObject(forEntityName: "Location", into: context)
// populate address
locationEntity.setValue(myLocations[i].coordinate.latitude, forKey: "latitude")
locationEntity.setValue(myLocations[i].coordinate.longitude, forKey: "longitude")
// create relationship Location -> Log
locationEntity.mutableSetValue(forKey: "log").add(logEntity)
}
self.saveContext()
self.myLocations.removeAll()
self.errors = 0
}
}
保存上下文功能
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}