Sorting a NSSet of NSManagedObjects by attribute

10,879

Solution 1

No, but you'd use an NSSortDescriptor.

You'd use the sortedArrayUsingDescriptors: method like this:

NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray *sorted = [yourSet sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];

Solution 2

By mentioning NSPredicate, I feel as though the OP wanted to sort the set as part of the executed fetch. Whether he meant this or not, here is an example of this. Say you have a to-many inverse relationship between an Employee entity and a Department entity i.e. a department contains many employees. Given you've fetched the department already, fetch the employees in the department and sort them by first name:

Using MagicalRecord:

Department *department = someFetchedDepartment; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"department == %@", department];
NSArray *sortedEmployees = [Employee MR_findAllSortedBy:@"firstName" ascending:YES withPredicate:predicate];

Without MagicalRecord:

NSFetchRequest *request = [[NSFetchRequest alloc] init];    

NSEntityDescription *employeeEntity = [NSEntityDescription @"Employee" inManagedObjectContext:self.context];
[request setEntity:employeeEntity];

Department *department = someFetchedDepartment; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"department == %@", department];
[request setPredicate:predicate];

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

NSError *error = nil;
NSArray *sortedEmployees = [self.context executeFetchRequest:request error:&error];
Share:
10,879
Bill Shiff
Author by

Bill Shiff

Updated on June 14, 2022

Comments

  • Bill Shiff
    Bill Shiff almost 2 years

    Given an NSSet that contains objects that are a subclass NSManagedObject with a string attribute called name, how can I sort the set by name? Is this where I would use an NSPredicate?

    Thank you!

  • Bill Shiff
    Bill Shiff over 13 years
    Thanks! Would these need to be released for memory management?
  • Jacob Relkin
    Jacob Relkin over 13 years
    @Bill The sorted array is autoreleased, so no.
  • BaSha
    BaSha over 9 years
    and if I create NSSet from sorted NSArray by NSSet(array: <#[AnyObject]#>)), will it keep order?
  • Demitri
    Demitri almost 8 years
    MagicalRecord: github.com/magicalpanda/MagicalRecord. OP really should have pointed this out as a third party solution.