简体   繁体   中英

Sort TableView by date while using Core Data

I want to sort my TableView by date. So that the newest entry is at the top. In the CoreData Entity is a current date attribute. I have tried this, but nothing happened:

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    NSManagedObjectContext *moc = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Body"];
    _body = [[moc executeFetchRequest:fetchRequest error:nil]mutableCopy];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date"
                                                                   ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];

    NSError *error = nil;
    NSArray *fetchedObjects = [moc executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"View Failed! %@ %@", error, [error localizedDescription]);
    }

    [self.tableView reloadData];

Thank you for answering!

Please note the comments that i've made in the code. That should be working now. Just a couple of notes:

  • It's good idea to read Apple Naming Conventions Guidelines
  • It's not good practice to get the MOC in this way, better way is to have a separate class that is Core Data Manager and handles all Core Data work.
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    NSManagedObjectContext *moc = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Body"];

//    You're updating your datasource but before setting the sort descriptor to the fetchRequest
//    Remove this line it's redundant
//    _body = [[moc executeFetchRequest:fetchRequest error:nil]mutableCopy];


    //Note that ascenging should be NO if you want the newest one to be on the top
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date"
                                                                   ascending:NO];

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];

    NSError *error = nil;
    NSArray *fetchedObjects = [moc executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"View Failed! %@ %@", error, [error localizedDescription]);
    }else{
        _body = [fetchedObjects mutableCopy];
    }

    [self.tableView reloadData];
}

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