且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Realm Swift2:分离模型和Realm模型类的***实践

更新时间:2023-12-01 20:43:58

(至少在iOS方面),官方没有建立将实际的Realm Object子类抽象为模型类逻辑的***实践.话虽如此,我肯定听说过过去为支持多种类型的数据框架而执行这种逻辑的应用程序.

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.

如果要执行此操作,我将为实现我自己的API的每个模型创建一个单独的对象类,以了解如何获取/设置数据属性,并将Realm对象设置为该对象的内部成员.然后,该对象将用作我的应用程序逻辑与如何将数据保存到Realm之间的通用接口.这样,如果我确实想在线下交换数据框架,则可以简单地用一个新的数据对象替换自己的数据对象,但保持API的一致性.

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.

关于您发布的错误消息,为了确保数据完整性,除非它在写事务中,否则您不能修改Realm对象(UI线程或其他).话虽如此,您可以在该抽象对象中非常容易地封装该逻辑(即在当前线程上打开Realm写事务).

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.