I just have started working with Realm for Swift. After reading the documentation, still I have a couple of question marks in mind.
My biggest one is, if there is a best practice for separation Model classes from Realm classes.
For example, in Java MVC projects we used DAO classes (Data Access Object classes) which were responsible for the communication with the database layer. Our corresponding model classes only have either the dao object injected or we used service classes for this (like CRUD operations).
If I habe a Realm “Model” class, this seems now to be everything in one. But after having the object persisted to the database, changing attributes of the object in the UI-Layer results in
'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
Which brings me back to my initial though: Shouldn’t this be separated in Realm objects and model objects. Or is it OK to have "realm.write" processes in View-Classes then?
I did some research on this but the results are very vage on this.
How do you deal with this in your projects. Do you have some kind of best practice or guidance?
Many thanks in advance John
Officially, (on the iOS side at least), there's no established best practice for abstracting the model class logic away from the actual Realm Object subclasses. That being said, I've definitely heard of apps in the past who do do this sort of logic in order to support multiple types of data frameworks.
If I were to do this, I would make a separate object class for each model implementing my own API on how to get/set data properties, and make the Realm object an internal member of this object. This object would then serve as the generic interface between my app's logic and how to save that data to Realm. That way, if I did want to swap out the data framework down the line, I could simply replace my own data object with a new one, but keep the API consistent.
In regards to that error message you posted, in order to ensure data integrity, you cannot modify a Realm object (UI thread or otherwise) unless it's in a write transaction. That being said, you could encapsulate that logic (i.e. open up a Realm write transaction on the current thread) pretty easily within that abstract object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With