CoreData仅在重新启动应用程序后更新?

时间:2016-09-29 06:00:32

标签: swift core-data

您好我使用AppDelegate模板生成的saveContext()保存数据。我的应用程序在后台模式下记录位置集,然后当应用程序进入前台时,我会将这些位置存储在核心数据中。一切都被保存并存储,但是当我进入我的视图控制器显示它们时,除非我重新启动应用程序并返回它,否则它不会显示。

 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)")
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可能没有刷新ViewController,因此在重新启动之前它仍会显示旧数据。