Jani
Jani

Reputation: 1490

Design pattern for Realm persistence

I'm using Realm in a App and I'm trying to abstract much as possible so that in the future I can swap database providers without too much change.

This pattern has worked well although I'm concerned about the following.

Upvotes: 7

Views: 1168

Answers (1)

TiM
TiM

Reputation: 15991

That's a completely solid design pattern. It's pretty common for developers to abstract the data layer APIs way from their code in case they need to switch it out.

In response to your questions:

  • You're correct. Realm object instances are internally cached, so you can easily call let realm = try! Realm() multiple times with very little overhead.
  • Unless you've found a specific reason, it's probably not necessary to call refresh() on the Realm instance every time you use it. Realm instances on the main thread are automatically refreshed on each iteration of the run loop, so you only need to call refresh() if you're expecting changes on a background thread, or need to access changes before the current run loop has completed.
  • 'Better' design patterns is probably a matter of opinion, but from what I've seen from other codebases, what you've got there is already great! :)

Upvotes: 5

Related Questions