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

Posted

技术标签:

【中文标题】CoreData 仅在我重新启动应用程序后更新?【英文标题】:CoreData only updates after I restart the app? 【发布时间】: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)")
        
    

【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于CoreData 仅在我重新启动应用程序后更新?的主要内容,如果未能解决你的问题,请参考以下文章

CoreData + CloudKit 仅在最小化和重新打开应用程序后同步

Tomcat Web 应用程序仅在我在 /manager 页面中明确启动后才能工作

回收站视图仅在我从房间数据库中删除后重新打开活动时更新

仅在需要时重新注册地理围栏

如何重新启动应用程序的更新循环

iCloud 仅在应用启动时更新