Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm and Diffable Data Source

Tags:

ios

swift

Has anyone tried to use Realm in conjunction with diffable data sources? There seems to be an issue I can't get my head around.

So, when when we use the "traditional" data source API, in cellForRowAt we get the object for a particular row on an index-based basis and since Realm returns objects inside its generic Results type (e.g. let items = Results<Item>), which conforms to Collection, we can basically access the element like always: items[indexPath.row]

However, when you use diffable data source and create a snapshot, you have it like this: var snapshot = NSDiffableDataSourceSnapshot<Int, Item>. You add a section by doing snapshot.appendSections([0]) and then you have to add items to that section. My main issue here is that you can't do snapshot.appendItems(items) since items is of type Results<Item>, not Array<Item>. Am I missing something here?

Also, Realm's Object class seems to have its own implementation of Hashable so I think there's no way of ensuring the uniqueness of objects apart from overriding Realm's primaryKey and implementing your own auto increment feature. All that seems a bit weird to me to the point where I'm thinking to switch to Core Data.

Haven't found similar topics on StackOverflow so any help will be much appreciated.

like image 584
Denis Prozukin Avatar asked Oct 14 '25 14:10

Denis Prozukin


1 Answers

You can covert Result<Items> to Array using an extension:

extension Results {
  func toArray() -> [Element] {
    return compactMap {
        $0
    }
  }
}

You can use it like: results.toArray() and it will give you the array and then with your case you can append data into it.

like image 180
Rob Avatar answered Oct 17 '25 07:10

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!