【问题标题】:CoreData only updates after I restart the app?CoreData 仅在我重新启动应用程序后更新?
【发布时间】:2016-09-29 06:00:31
【问题描述】:

您好,我正在使用 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)")
        }
    }
}

【问题讨论】:

    标签: swift core-data


    【解决方案1】:

    您可能没有刷新您的 ViewController,因此它仍然显示旧数据,直到您重新启动。

    【讨论】:

      猜你喜欢
      • 2011-05-15
      • 2012-05-30
      • 2017-06-27
      • 2018-11-30
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多