October 2013
Intermediate to advanced
1053 pages
28h 7m
English
You want to sort the managed objects (records) that you fetch from a managed object context (database).
Create instances of NSSortDescriptor for each attribute (column,
in the database world) of an entity that has to be sorted. Add the sort
descriptors to an array and assign the array to an instance of NSFetchRequest using the setSortDescriptors: instance method. In this
example code, Sorting_Data_in_Core_DataAppDelegate is the
class that represents the app delegate in a universal app. To understand
how the Person entity is created,
please refer to Recipes 18.1 and 18.2:
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{[selfcreateNewPersonWithFirstName:@"Richard"lastName:@"Branson"age:61];[selfcreateNewPersonWithFirstName:@"Anthony"lastName:@"Robbins"age:51];/* Create the fetch request first */NSFetchRequest*fetchRequest=[[NSFetchRequestalloc]initWithEntityName:@"Person"];NSSortDescriptor*ageSort=[[NSSortDescriptoralloc]initWithKey:@"age"ascending:YES];NSSortDescriptor*firstNameSort=[[NSSortDescriptoralloc]initWithKey:@"firstName"ascending:YES];fetchRequest.sortDescriptors=@[ageSort,firstNameSort];NSError*requestError=nil;/* And execute the fetch request on the context */NSArray*persons=[self.managedObjectContextexecuteFetchRequest:fetchRequesterror:&requestError];for(Person*personinpersons){NSLog(@"First Name = %@",person
Read now
Unlock full access