Vyacheslav
Vyacheslav

Reputation: 27211

Realm data synchronization

Please, explain the behavior.

If I want to update some data using Realm I have to do something like this:

let realm = try! Realm()
  let theDog = realm.objects(Dog.self).filter("age == 1").first
  try! realm.write {
    theDog!.age = 3
  }
}

But what happens if I just do this: theDog!.age = 3 ? will theDod data be out of sync? How can I update this element later?

try! realm.write {
//what I have to write here?
  }

Is there any way to force sync each element changing? Is there any disadvantage to use force sync if it exists?

Upvotes: 0

Views: 943

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81529

Please excuse my Swift if I mess it up, I'm not too familiar with the syntax.

While I know this is the example code, I don't actually like it much.

let realm = try! Realm()
  let theDog = realm.objects(Dog.self).filter("age == 1").first
  try! realm.write {
    theDog!.age = 3
  }
}

The query should be inside the transaction block to ensure that you're modifying the latest version of the object.

let realm = try! Realm()
  try! realm.write {
    let theDog = realm.objects(Dog.self).filter("age == 1").first
    theDog!.age = 3
  }
}

Now, I think your question is why realm.write { is needed. It's because you can modify managed RealmObjects only in a transaction.

Transaction is required to ensure that a particular thread's Realm instance is switched to "write mode", and there can only be one Realm instance in "write mode" at a given time. As a result of this, a version seen by a given Realm instance will always remain consistent, and doesn't change - only when Realm syncs itself to a new version.

This is how Realm is designed so that you can create new versions of the Realm easily on a background thread, which then automatically syncs up to other Realm instances.

When a transaction is committed, then when this change occurs, a message is sent to other threads (if they can receive a message, anyways - requires an event loop, for example the UI thread has one) telling the Realm instances on those threads to update themselves; and to call all change listeners of all result sets and managed RealmObjects to indicate that they've too been updated (if they changed with this transaction).


So to answer your question, the properties you change are changed in all RealmObjects that belong to the same object.

let realm = try! Realm()
  let originalDog = realm.objects(Dog.self).filter("age == 1").first
  try! realm.write {
    let theDog = realm.objects(Dog.self).filter("age == 1").first
    theDog!.age = 3
  }
  // assuming there is only 1 dog with age==1, 
  // originalDog!.age will be 3
}

I think the "force sync" you speak of is a primary feature of Realm.

Upvotes: 1

Related Questions