Realm Swift2: Best practice for model and Realm model class separation

回眸只為那壹抹淺笑 提交于 2019-12-10 01:47:54

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/33592572/realm-swift2-best-practice-for-model-and-realm-model-class-separation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!