Search code examples
iosobjective-crealmgithub-mantlerealm-cocoa

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:

In order to use the Mantle library, the model interface must extend the MTLModel class like this:

@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:

@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.

is there a way to avoid this kind of duplication?


Solution

  • 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).

    Finally to use it, you just need to subclass it.