Oxygen
Oxygen

Reputation: 11

Persist different objects (types) as single object - CoreData - (Favorites example)

My question is how to implement this correctly and with good design.

I would use Core Data for this.

Problem description: Let's suppose that we have two object types (classes) in the system, Location and Event. They are retrieved from webservice, and there is no need to persist it.

Any of these two kind of objects can be added (saved) to favorites and it should be persisted locally.

Additional requirements:

I have a dilemma about the best way to implement this. Should I store locations and events directly as separate entities (model objects), and somehow retrieve it in a single fetch, in order to get and manage the list of favorites. Or, maybe use an interface/protocol (for example Favorable), and create and store Favorite objects, and each object which can be added to favorite should implement favorable and will be converted to Favorite object, but in this case, it will limit favorites to only attributes that Favorite object exposes.

Upvotes: 1

Views: 108

Answers (1)

Mundi
Mundi

Reputation: 80273

You should make a simple Core Data model with the two entities. It is very straight forward. Your table view would have two type of cells (with different identifiers) that display the data as needed.

You can use these to entities (subclasses of NSManagedObject) throughout your app. You should perhaps persist them anyway (so they are available if the internet goes down and allow the user to continue working with them). The favourite instances can be marked with a BOOL property.

One design consideration, though: maybe you want to create an optional relationship between Location and Event. Some events might be tied to a particular location and you will need this info as well. With Core Data this is really easy to do.

Upvotes: 1

Related Questions