Smart Home Smart Home - 2 months ago 5x
Objective-C Question

Realm as data source for Tableview - how to store different objects in data source

I am using Realm as my storage layer in an iOS app. App has a table view in which each cell can be one of two types. The two types have some fields in common but several fields are different.

The client will perform a REST API with a search term and the server will return a prioritized list of objets belonging to the two types. The designer does not want the object to displayed as two separate groups but intermingled together based on priority determined by the server.

I want to store the results in the Realm DB. Since Realm

does not allow me to store objects of 2 types, to model this in Realm, it appears that I need to have three
of objects of type 1
of objects of type 2
of objects of a 3rd type that has two fields: Object Type and ObjectID (this is the one that stores the intermingled version).

Is there a different approach that reduces the duplication?

ast ast

The 3rd type could be a wrapper object with direct relationships to the two other types:

@interface Obj1 : RLMObject

@interface Obj2 : RLMObject

@interface Wrapper : RLMObject
@property Obj1 *o1;
@property Obj2 *o2;

When receiving the objects you would create an instance of the wrapper for each and only set the matching link. Then your TableView could just check which link is valid and display the context of the linked object.

Depending on your use case you wouldn't even need RLMArrays for the two main object types, as ordering is maintained by the list of wrapper objects.