我有一个包含节标题和节行的tableview。 我试图用不同的键路径对标题和行进行排序。我希望标题按日期排序,并且要按不同的键路径排序。
-(NSFetchRequest *)entryListFetchRequest{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"NapEntry"];
[fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO],
[NSSortDescriptor sortDescriptorWithKey:@"timePicker" ascending:NO selector:@selector(compare:)]]];
return fetchRequest;
}
标题正确排序,但行不排序。行是按时间排序的NSDate。现在他们只是按输入顺序排序,而不是按时间排序。
-(NSFetchedResultsController *)fetchedResultsController{
if(_fetchedResultsController != nil){
return _fetchedResultsController;
}
CoreDataStack *coreDataStack =[CoreDataStack defaultStack];
NSFetchRequest *fetchRequest = [self entryListFetchRequest];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:coreDataStack.managedObjectContext sectionNameKeyPath:@"sectionName" cacheName:nil];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
这是我的cellForRow方法:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
NapCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NapEntry *entry = [self.fetchedResultsController objectAtIndexPath:indexPath];
[cell configureCellForEntry:entry];
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
为什么第二个sortDescriptorWithKey“timePicker”没有排序表行的任何想法?
ADDED实体的NSManagedObject子类*
#import "NapEntry.h"
@implementation NapEntry
@dynamic date;
@dynamic timePicker;
@dynamic timer;
//assigns section headers
- (NSString *)sectionName {
NSDate *date = [NSDate dateWithTimeIntervalSince1970:self.date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE MMM d, yyyy"];
return [dateFormatter stringFromDate:date];
}
@end
答案 0 :(得分:0)
NSFetchedResultsController
对象sectionNameKeyPath属性值必须对应NSFetchRequest
第一个排序描述符,即指定节标题的方式。其余的排序描述符用于对每个部分中的行进行排序。
所以基本上你应该可以试试这个:
NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:@"sectionName" ascending:NO];
NSSortDescriptor *sd2 = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
NSSortDescriptor *sd3 = [NSSortDescriptor sortDescriptorWithKey:@"datePicker" ascending:NO]; // note sure compare: is needed
[fetchRequest setSortDescriptors:@[sd1, sd2, sd3];
这假设你的模型对象有一个sectionName属性,你要按部分排序。