简体   繁体   English

Realm + Mantle:在集成两个框架时如何避免多重继承重复?

[英]Realm + Mantle: how to avoid multiple inheritance duplication when integrating both frameworks?

I have a simple scenario where I want to parse a User model from Json with Mantle and persist it to a realm database: 我有一个简单的场景,我想用Mantle从Json解析一个User模型并将其持久化到一个领域数据库:

In order to use the Mantle library, the model interface must extend the MTLModel class like this: 为了使用Mantle库,模型接口必须扩展MTLModel类,如下所示:

@interface User: MTLModel<MTLJSONSerializing>
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *email;
@end

and in order to persist that model in realm, I have to declare a second interface that extends from RLMObject : 为了在领域中保持该模型,我必须声明从RLMObject扩展的第二个接口:

@interface RLMUser:RLMObject
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *email;
@end

As you see I had to implement another type of the User class because I have to extend RLMObject . 如您所见,我必须实现另一种类型的User类,因为我必须扩展RLMObject

is there a way to avoid this kind of duplication? 有没有办法避免这种重复?

Hmmm, you COULD try creating a single class that inherits from both classes down a chain as long as RLMObject is the highest superclass (eg User > MTLModel > RLMObject ) and seeing if that works. 嗯,你可以尝试创建一个单独的类,只要RLMObject是最高的超类(例如User > MTLModel > RLMObject )并且查看是否有效,它就会从链中的两个类继承。 If MTLModel only works on its data through key-path values, Realm might be able to handle working with it like that. 如果MTLModel仅通过键路径值处理其数据,则Realm可能能够像这样处理它。

But in all honesty, if you want to ensure that both classes behave properly as intended, it's probably best not to mix them, and simply copy the data across them when needed. 但是说实话,如果你想确保两个类都按预期正常运行,最好不要将它们混合在一起,只需在需要时将数据复制到它们之间。

Thankfully, because RLMObject instances exposes all of the properties it persists through an RLMObjectSchema object, you don't need to manually copy each property manually, and can do it with a pretty minimal amount of code: 值得庆幸的是,因为RLMObject实例公开了它通过RLMObjectSchema对象持久保存的所有属性,所以您不需要手动手动复制每个属性,并且可以使用极少量的代码来完成:

User *mantleUser = ...;
RLMUser *realmUser = ...;

// Loop through each persisted property in the Realm object and 
// copy the data from the equivalent Mantle property to it
for (RLMProperty *property in realmUser.objectSchema.properties) {
   id mantleValue = [mantleUser valueForKey:property.name];
   [realmUser setValue:mantleValue forKey:property.name];
}

Base on the idea of using the protocol, I created a super class ( gist here ): 基于使用协议的想法,我创建了一个超类( 这里的要点 ):

@interface ModelBase : RLMObject <MTLJSONSerializing, MTLModel>

Then as @David Snabel-Caunt said, I ended up implementing some functions of the MTLModel class (copy-paste from MTLModel.m). 然后正如@David Snabel-Caunt所说,我最终实现了MTLModel类的一些功能(来自MTLModel.m的复制粘贴)。

Finally to use it, you just need to subclass it. 最后要使用它,你只需要子类化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM