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

问题描述:

您好我保存我的数据使用与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)") 
     } 
    } 
} 

你可能不刷新您的ViewController所以还是显示,直到你重新启动旧数据。