iOS
app that uses CoreData
Animal
Lion
, Tiger
and Elephant
Car
, Bike
. Note : Only one record can be marked as favourite at a given time
Animal
called isFavourite
. isFavourite
as true
. Favourite
and have a dummy row in it. Favourite
to Animal
called animal
. 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.