NSSortDescriptor

NSSortDescriptor has been around longer than Core Data, and it’s still quite useful for ordering data. As mentioned previously, data that comes from a to-many relationship is unordered by default, and it’s up to us to order it. So, if we wanted to retrieve all the recipes and sort them by their name property in alphabetical order, we’d require another step as part of the fetch.

 let​ fetch = ​NSFetchRequest​(entityName: ​"Recipe"​)
 fetch.sortDescriptors = [​NSSortDescriptor​(key: ​"name"​, ​as​cending: ​true​)]

In this example, we are retrieving all the Recipe entities by creating an NSFetchRequest with the NSEntityDescription set to our entity and no predicate. However, in addition to fetching the Recipe entities, we want ...

Get Core Data in Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.