Noah Iarrobino
Noah Iarrobino

Reputation: 1553

Sorting a relationship in CoreData

I have a deck entity, with many cards belonging to that deck. The Cards entity has an attribute named score in which I want to sort a decks' cards by this score value. This is what I've tried:

    var cards = deck.cards?.allObjects as! [Cards]
    cards.sort(by: {$0.score > $1.score})
    deck.cards?.allObjects as! [Cards] = cards

but am getting this error Cannot assign to immutable expression of type '[Cards]' since you cannot assign the relationship. Is there a way to sort this in real time or as a relationship rule in the data model?

edit: I know it can be done with a fetch request, but I am trying to avoid a fetch request since this operation will be have to be done pretty often

Upvotes: 0

Views: 348

Answers (1)

Exception
Exception

Reputation: 785

When you use a fetch request to get the decks, all the cards relationships within the deck are faulted objects. That means, when you access the cards through the decks, another access to the database is done.

This is expensive compared to one fetch request where you specify the deck and the order. Core Data (or better sqlite) is smart enough to cash the fetch request results is no change happened.

I would advise using fetch requests and try to fix the optimization problem when you face it.

You can fix the error you are getting by

let sortedCards = cards.sorted { $0.score > $1.score }
deck.cards = sortedCards

One more thing: To preserve the order of the cards in the database you need to use an NSOrderedSet

Upvotes: 1

Related Questions