简体   繁体   中英

CoreData mark one record as favourite (mutually exclusive)

Overview:

  • I have an iOS app that uses CoreData
  • There is an entity called Animal
  • It has a set of records Lion , Tiger and Elephant
  • I would like to mark only one of the records as favourite.

Similar entities with the same approach:

  • Similarly I could have other entities such as Car , Bike .
  • Each entity would have a set of records.
  • Again each entity should only have one favourite record

Reason:

  • App has an option to create a new document
  • When the new document is created, it would be populated with default values for each entity (by selecting the favourite record of each entity)

Note : Only one record can be marked as favourite at a given time

Possible models I thought of:

1. Field called isFavourite

  • Create a field in Animal called isFavourite .
  • Mark only one of the rows as isFavourite as true .
  • Much of the logic to maintain isFavourite is managed in code.

2. Separate entity called Favourite

  • Create a separate table called Favourite and have a dummy row in it.
  • Establish a relationship from Favourite to Animal called animal .
  • This will point to the favourite record.

Questions:

  1. What is the preferred approach to tackle this problem ?
  2. Are there any other alternatives ?

Go with option 2, maybe call it Config. If you want to ensure it is just a singleton add a attribute that is unique and can only be zero.

You can write a helper computed var returning true if the reverse relationship is non-nil.

Main advantage of option 2 is the simplicity of changing the favourite, you don't have to scan through all the items to to set them non-favourite just change it on the singleton config.

Give some thought to other parts of the app and to what you might want to do in the future.

Adding a field: Works OK but requires some code to maintain, which might be error prone. On the other hand maybe one day the app might allow multiple favorites, and this will just work with that.

Using a separate entity: Also works OK but adds a whole new entity where you'll only have a single instance. In general, if you have an entity where you only ever want one instance, you're doing it wrong. On the other hand this also works well with the potential for multiple favorites.

A third approach is to save the objectID for the favorite animal somewhere outside of Core Data, like UserDefaults . Save it, and then find the favorite by using NSManagedObjectContext 's existingObject(with:) method. You can't save the NSManagedObjectID directly but you can get its uriRepresentation() and save that.

I'd probably go with #1 in most cases but it depends what else I need in the app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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