1

I am adding to a simple entity, a list of names (from an array). But before saving the entity, I would like them to be sorted. Please could someone be so kind as to tell me how to do this?

I've seen how to sort some fetched data, but I do not know how to do this. A written example would be greatly appreciated. Many thanks.

NSManagedObjectContext *context = [self managedObjectContext];
NSString *myTempString;

for (databaseMakerVC *aName in peoplesNames.theArray) {
    myTempString = [[NSString alloc] initWithFormat:@"%@", aName];

    peoplesNamesObject *newObject = [NSEntityDescription
                                     insertNewObjectForEntityForName:@"peoplesNamesObject"
                                     inManagedObjectContext:context];
    newObject.aName = myTempString;
}


    // *** Do the sorting here!? ***


// Save the context
NSError *error = nil;
if (![context save:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
Custom Bonbons
  • 1,609
  • 2
  • 12
  • 17
  • take a look at : http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it – Damien Locque Jul 05 '12 at 15:16
  • Why do you need to sort before saving? Any reasons? Thanks. – Lorenzo B Jul 05 '12 at 15:17
  • as far as i know, you dont gain any performance improvement if you sort before saving. That doesnt mean that you cannot sort the items for other reasons. – scord Jul 05 '12 at 15:19
  • @Flex_Addicted because Core Data is saving them in the entity in a random fashion. I want them in a particular order. – Custom Bonbons Jul 05 '12 at 15:30
  • @luxsypher the page is just discussing sorting an array. My problem is the data is added to the entity jumbled. (Even thought the source array is ordered!) – Custom Bonbons Jul 05 '12 at 15:50

2 Answers2

2
 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription 
                                   entityForName:@"peoplesNamesObject" inManagedObjectContext:context];

 [fetchRequest setEntity:entity];


     NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"aName" ascending:YES]; 

        NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 

        [fetchRequest setSortDescriptors:sortDescriptors]; 

        NSError *error;


       NSArray *array=[context executeFetchRequest:fetchRequest error:&error]; 

This will work

Dinesh Kaushik
  • 2,917
  • 2
  • 23
  • 36
0

EDIT

Just add a sort descriptor after you insert the object

The sortDescriptorWithKey looks for a key in the array. In a array I created I assigned a key to "createdDate" and sorted it by that. So you would assign a key of "name" and use the code below

NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
[peoplesNames.theArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
BigT
  • 1,413
  • 5
  • 24
  • 52