核心数据:在一对多关系中按计数排序 [英] Core Data: sorting by count in a to-many relationship
问题描述
我目前正在尝试设置一个NSFetchedResultsController,它将基于一对多关系中的实体数量来排序我的表视图。我不知道这是否会在计数时产生差异,但这也是一个反比关系。
I am currently trying to setup a NSFetchedResultsController that will order my table view based on the number of entities in a to-many relationship. I am not sure if this makes a difference when counting, but this is also an inverse relationship.
我以为这样的工作很好:
I thought something like this would work just fine:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Parent"
inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc]
initWithKey:@"children.@count" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1,
nil];
[fetchRequest setSortDescriptors:sortDescriptors];
我不断收到包含KVC集合的Keypath,未能处理孩子。@ count'。
I keep getting 'Keypath containing KVC aggregate where there shouldn't be one; failed to handle children.@count'.
对可能出错的任何想法?
Any ideas on what could be going wrong?
推荐答案
据我所知,你不能在查询中应用@count,但是你可以很容易地将它应用到抓取的数组。
AS far as I know you can't apply the @count in the query, but you can easily apply it to the fetched array.
NSEntityDescription * entity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
NSError *error;
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"children.@count" ascending:NO];
NSArray *descriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
NSArray *sortedArray = [results sortedArrayUsingDescriptors:descriptors];
这篇关于核心数据:在一对多关系中按计数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!