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
}
}
コンテキスト機能を使用すると、再起動するまで、それはまだ古いデータを示しているように、あなたはおそらくあなたのViewControllerをリフレッシュされていません
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)")
}
}
}