WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: NSSortDescriptor with NSSet count?

Forums > iOS

Is it possible to sort by the counts of one NSSet of entity?

For example:


  • Items (to-many)

    In NSPredicate, it is possible to useitems.@count, but this form get error in NSSortDescriptor keypath.

    ( NSSortDescriptor(key: "items.@count", ascending: ascending))

items.count will also fail,

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'

Does it mean it is Impossible to sort by counts with NSSortDescriptor?



had you considered adding a derived attribute to the entity (on the one-side of the relationship) named itemCount to keep the count of items (on the to-many side of the relationship)? that might solve the sort descriptor issue.

see WWDC2019 video Session 230, Making Apps with Core Data at around the 19:00 mark.

hope that helps,



That's brilliant idea, thank you so much!

Thank you for finding the video with timestamp for me too, didn't know that before ( mainly start 2020) , now I learnt new things :)


Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.