我有一个表视图控制器,其中包含由fetchResultsController处理的队形列表。

这是我的核心数据实体的样子:



我尝试通过dateRange对我的fetchResultsController进行排序,如下所示:

// |fetchedResultsController| custom setter
- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:self.fetchRequest managedObjectContext:self.mainManagedObjectContext sectionNameKeyPath:@"dateRange" cacheName:kFormationsFetchedCacheName];
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;
}

// |fetchRequest| custom setter
- (NSFetchRequest *)fetchRequest {
    if (_fetchRequest != nil) {
        return _fetchRequest;
    }

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"student == %@", self.currentStudent];
    NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"dateRange" ascending:NO];
    NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];

    _fetchRequest = [[NSFetchRequest alloc] initWithEntityName:kBSFormation];
    _fetchRequest.predicate = predicate;
    _fetchRequest.sortDescriptors = [NSArray arrayWithObjects: dateDescriptor, nameDescriptor, nil];

    return _fetchRequest;
}


当我尝试添加第一个Formation时,一切都很好,但是接下来的错误是:

2013-01-30 22:43:08.370 [7202:c07] -[BSDateRange compare:]: unrecognized selector sent to instance 0x81781a0

2013-01-30 22:43:08.371 [7202:c07] CoreData: error: Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  -[BSDateRange compare:]: unrecognized selector sent to instance 0x81781a0 with userInfo (null)

2013-01-30 22:43:08.372 [7202:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[BSDateRange compare:]: unrecognized selector sent to instance 0x81781a0'


如果我对以下行发表评论:NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"dateRange" ascending:NO];,它正在工作,但是由于sectionNameKeyPath设置为dateRange,我的表视图混乱了

有人正在弄清楚这是什么问题? :/

最佳答案

您要告诉它根据dateRange关系进行排序。但是dateRangeBSDateRange有关系,Core Data如何比较它们?它应该使用from还是to或它们的某种组合?您不能仅仅告诉它对这样的对象进行排序,因为尚不清楚排序的工作方式。

相反,首先要弄清楚排序的含义。然后适当地修改您的排序描述符。例如,如果您决定排序取决于from值,则更改排序描述符以使用键路径指向from

NSSortDescriptor *dateDescriptor = [NSSortDescriptor
    sortDescriptorWithKey:@"dateRange.from"
    ascending:NO];


如果需要基于fromto进行排序,请使用多个排序描述符。

10-05 19:17