簡體   English   中英

使用Core Data時按日期對TableView進行排序

[英]Sort TableView by date while using Core Data

我想按日期對TableView進行排序。 因此,最新條目位於頂部。 在CoreData實體中是當前日期屬性。 我已經嘗試過了,但是什么也沒發生:

-(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];

感謝您的回答!

請注意我在代碼中所做的注釋。 現在應該可以了。 只是一些注意事項:

  • 閱讀Apple命名約定指南是個好主意
  • 以這種方式獲取MOC並不是一個好習慣,更好的方法是擁有一個單獨的類,即Core Data Manager,並處理所有Core Data工作。
-(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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM