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. For example, if we wanted to retrieve all the recipes and sort them by their name property in alphabetical order, we’d require an additional step as part of the fetch.

RecipesV1/PPRecipes/PPRMasterViewController.m
 NSFetchRequest *fetchRequest = nil;
 fetchRequest = [NSFetchRequest fetchRequestWithEntityName:​@"Recipe"​];
 
 NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:​@"name"
  ascending:YES];
 [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

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 them sorted. We accomplish the sorting by adding an NSArray of NSSortDescriptor instances directly to the NSFetchRequest, which cause the returned NSArray to be properly sorted.

The NSSortDescriptor takes two parameters as part of its ‑init: a key and a BOOL denoting whether the sort is ascending or descending. We can have as many NSSortDescriptor objects as we want as part of the sort, and therefore they’re placed within an NSArray prior to the sort being performed.

Adding an NSSortDescriptor is especially useful on Cocoa Touch because the NSFetchedResultsController continues to keep its results sorted without any intervention on our part. The NSFetchedResultsController is discussed in more depth in Chapter 3, iOS: NSFetchedResultsController.