2

Let's say I have 5 objects from api.

I store them using realm.add(item, update: true) which will create or update 5 objects.

Next time, one item is removed from server side.

So when I call api afterward, total number of realms objects should be 4. Not 5.

Using realm.add(item, update: true) will not remove the un-included items from api. It stores only add or update.

What's the best way to handle that?

Devyn
  • 2,255
  • 7
  • 32
  • 40
  • I use this trick https://stackoverflow.com/a/39352718/2413303 but the code is written in Java. Still applicable, in fact you even have `setValue` method which makes it much easier. – EpicPandaForce Jun 01 '17 at 16:50

1 Answers1

3

This is conceptually quite simple, just keep track of the objects you see from your server response and delete the rest:

var objectsToDeleteIDs = Set(realm.objects(Item.self).value(forKey: "id") as! [String])
realm.begineWrite()
for item in serverItems {
  realm.add(item, update: true)
  objectsToDeleteIDs.remove(item.id)
}
let objectsToDelete = realm.objects(Item.self).filter("id IN %@", objectsToDeleteIDs)
realm.delete(objectsToDelete)

try realm.commitWrite()
jpsim
  • 14,329
  • 6
  • 51
  • 68
  • Would be faster using `.map`and appending every ID on a list instead removing? Then delete it using the same code. – Pedro Paulo Amorim Jun 02 '17 at 15:37
  • 1
    There are certainly many other ways to accomplish the same thing, including some that take a more functional approach. Feel free to refactor to match the style you like, or to improve the performance in your use case. – jpsim Jun 02 '17 at 17:48