0

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?

3
  • Why you don't sort while calling the Database? Commented Mar 28, 2014 at 15:19
  • It's a pre-built app that I am maintaining. I can't figure out where the query for this table in the database is being called. Like I would have modified the SQL to sort by the orderNum. Any idea, how I can trace it in the program? Commented Mar 28, 2014 at 15:28
  • 1
    @user3473089 If you are now maintaining this code, it appears that a top priority would be reading the Core Data Programming Guide. Commented Mar 28, 2014 at 16:41

2 Answers 2

1

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 ]];
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, this is the right approach - and it's worth noting that having SQL engine do the sort as part of the fetch will be WAY faster and more efficient than retrieving the data and then sorting it in code. Especially if you're sorting on a column that has an index in SQL-land...
Do you know how I can access the SQL engine?
You have no direct access to SQL through Core Data. Calling executeFetchRequest: converts the fetch request to SQL and runs it (privately).
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.