我有一个简单的场景,我想用 Mantle 从 Json 解析一个用户模型并将其保存到 Realm 数据库:
为了使用 Mantle 库,模型接口(interface)必须像这样扩展 MTLModel 类:
@interface User: MTLModel<MTLJSONSerializing>
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *email;
@end
为了在 Realm 中保留该模型,我必须声明从 RLMObject 扩展的第二个接口(interface):
@interface RLMUser:RLMObject
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *email;
@end
如您所见,我必须实现另一种类型的 User 类,因为我必须扩展 RLMObject。
有没有办法避免这种重复?
最佳答案
嗯,只要 RLMObject 是最高的父类(super class)(例如 User > MTLModel > RLMObject) 看看是否可行。如果 MTLModel 仅通过键路径值处理其数据,Realm 可能能够像那样处理它。
但老实说,如果您想确保这两个类都按预期正常运行,最好不要将它们混合使用,并在需要时简单地在它们之间复制数据。
值得庆幸的是,因为 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];
}
关于ios - Realm +地幔: how to avoid multiple inheritance duplication when integrating both frameworks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37461076/