LoginSignup
1
0

More than 5 years have passed since last update.

Realm object の update の注意点

Posted at

はじめに

Android アプリを開発している際、Realmを用いてデータの更新をしようとすると、

Cannot modify managed objects outside of a write transaction.
というエラーが出力された。

なぜ?

エラー概要

トランザクション外でデータベースの更新を行ってしまったため。

...
DBの更新処理
...

realm.beginTransaction()
realm.copyToRealmOrUpdate(DB)
realm.commitTransaction()

トランザクションとは

簡単にいうと、
結果の整合性が必要な複数処理のこと。

つまり、エラーの原因は?

トランザクションの成功が必要であるにも関わらず、ある処理を分離すると整合性が取れなくなり、トランザクションに失敗してしまうため。

解決策

トランザクション内で更新処理を行うこと。

具体例

realm.beginTransaction()

...
DBの更新処理
...

realm.copyToRealmOrUpdate(DB)
realm.commitTransaction()

参考

「トランザクション」とは何か?を超わかりやすく語ってみた!

1
0
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
0