PanicDev
PanicDev

Reputation: 325

Sorting in Core Data, how to?

Currently, I have a core data model that is displayed in a table view. How do I sort the results by category, which is one of the entries in the core data model? Thanks in advance!

Upvotes: 1

Views: 1009

Answers (1)

Dan Shelly
Dan Shelly

Reputation: 6011

Have you read the Core Data Programming Guide?

The secret is to set a NSSortDescriptor on your NSFetchRequest by the property you wish to sort by.
For exmple:

Edit: (the entire example from the docs)

NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
                                          entityForName:@"Employee" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];

// Set example predicate and sort orderings...
NSNumber *minimumSalary = ...;
NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"(lastName LIKE[c] 'Worsley') AND (salary > %@)", minimumSalary];
[request setPredicate:predicate];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                    initWithKey:@"firstName" ascending:YES];
[request setSortDescriptors:@[sortDescriptor]];

NSError *error;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
    // Deal with error...
}

Upvotes: 4

Related Questions