1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftDataで、保存したはずのデータが勝手に消えてしまうことがある時の解決策??

Last updated at Posted at 2023-12-25

アプリでしっかり保存したはずのデータが再起動すると消えているので、なんだこれ???となっていました。

簡易的にmodelContainerを作成する場合は、以下のように、オートセーブの設定を変更できますよね。

WindowGroup {
    ContentView()
}
.modelContainer(for: User.self, isAutosaveEnabled: false) 
.modelContainer(for: User.self) //指定しない場合のデフォルトはtrueか?

しかし、どうやら自作で、Contextを作成した場合は、オートセーブがデフォルトでは無効になっていることがあるようです。

let newContext = ModelContext(container)
print(newContext.autosaveEnabled)
newContext.autosaveEnabled = true //明示的に自動保存を有効にする

ちなみに私の環境で、一度実行してみたときは最初から、自動保存が有効になっていましたが、たまに保存したはずのデータが消えていたりしたので、もしかしたら、SwiftData様の御気分で変わってしまうのか??😂こればかりはよくわからないので、一応trueに設定しておいた方がいいかもしれません。

よくわかりません>_<

ちなみに安全策は、try context.save()で明示的に保存することです。面倒ですが、書けば保存はされると思います。

参考

あと、バックグラウンドスレッドの ModelContextも自動では保存してくれないみたいです。
以下参照

ドキュメントにも記載があります。

デフォルトはfalseだが、mainContextの場合のみtrueになるというなんとも罠な仕様

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?