Reputation: 1
I have an array coming from Core Data that I want to sort, using an orderNum
field that I added to the database (Scene
entity).
I make the following request to get data:
NSArray *scenes;
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Scenes" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
scenes = [context executeFetchRequest:fetchRequest error:&error];
return scenes;
How do I go about sorting the data returned in scenes
by orderNum
?
Upvotes: 0
Views: 79
Reputation: 8225
The best approach is to retrieve the data from the Database sorted. Check @Wain answer for that.
However it is possible to sort the data into an NSArray
of dictionaries, too:
NSSortDescriptor *sceneDescriptor = [[NSSortDescriptor alloc] initWithKey:@"orderNum" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject: sceneDescriptor];
NSArray *sortedArray = [scene sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray = %@", sortedArray);
Upvotes: 0
Reputation: 119031
Use an NSSortDescriptor
with orderNum
as the key
and apply that sort descriptor to your fetchRequest
.
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"orderNum" ascending:YES];
[fetchRequest setSortDescriptors:@[ sort ]];
Upvotes: 1