简体   繁体   中英

Sort data entries in CoreData

When I'm using CoreData database, I realize that the data is not store in order. For example, if I store "Project 1", "Project 2", "Project 3", "Project 4", and then fetch them back in the view controller, the order I'm getting is 2, 3, 4, 1 . It turns out to be annoying since the display of these data is messed up. How do I sort the data so that they could come out in order?

Here is an example of a fetch using NSSortDescriptor.

 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
 NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
 NSEntityDescription *entity = [NSEntityDescription entityForName:@"CaseType" inManagedObjectContext:context];
 [fetchRequest setEntity:entity];

 NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"caseType" ascending:YES];
 [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDesc]];

 NSPredicate *activePred = [NSPredicate predicateWithFormat:@"active == 1"];
 [fetchRequest activePred];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM