[英]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.