我想按日期对TableView进行排序。因此,最新的条目位于顶部。 在CoreData Entity中是当前日期属性。我试过了,但没有发生任何事情:
-(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];
感谢您的回答!
答案 0 :(得分:0)
请注意我在代码中所做的评论。那应该是现在的工作。 只是几个笔记:
- 阅读Apple Naming Conventions Guidelines
是个好主意- 以这种方式获取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];
}