计算核心数据与多个关系



我正试图通过核心数据中的聚合函数进行排序。我有一个模型,它有实体Recipe和Food,它们之间有多对多的关系。我从一个查询开始,该查询列出了包含我列出的食物的食谱。到目前为止,我有:

NSExpression* key_path_exp = [NSExpression expressionForKeyPath:@"recipeName"];
NSExpression *countExpression =  [NSExpression expressionForFunction: @"count:"
                                                           arguments: [NSArray arrayWithObject:key_path_exp] ];
// Count the number of specified foods that this recipe contains, by counting the grouped by recipeName
NSExpressionDescription *count_description = [[NSExpressionDescription alloc] init];
[count_description setName: @"count"];
[count_description setExpression: countExpression];
[count_description setExpressionResultType: NSInteger32AttributeType];
// Which of the columns I'm interested in
NSAttributeDescription* recipe_name_column = [_fetchRequest.entity.attributesByName objectForKey:@"recipeName"];
[_fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:recipe_name_column, count_description,  nil]];
// Group by the recipe name
[_fetchRequest setPropertiesToGroupBy:[NSArray arrayWithObject:recipe_name_column]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY %K IN %@",@"foods",foods];
[_fetchRequest predicate];
// Required for group by
[_fetchRequest setResultType:NSDictionaryResultType];
NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"healthFactor" ascending:NO];
[_fetchRequest setSortDescriptors:@[sortDescriptor]];
NSError *error = nil;
if (![_fetchedResultsController performFetch:&error])
{
    // Update to handle the error appropriately.
    NSLog(@"Unresolved error %@, %@", error.localizedDescription, [error userInfo]);
    exit(-1);  // Fail
}

哪个生成SQL:

SELECT t0.ZRECIPENAME, COUNT( t0.ZRECIPENAME) FROM ZRECIPE t0 GROUP BY  t0.ZRECIPENAME ORDER BY t0.ZHEALTHFACTOR DESC

输出示例:

Old-school venison pie with juniper, rosemary & bay|5
Oriental pork with noodles|7
Pad Thai|3
Pint of prawns|10
Potato Gnocchi|7
Pumpkin Flan Recipe|12

当直接连接到sqlite数据库时,我可以编辑查询,使ORDER BY变成:

ORDER BY count(t0.ZRECIPENAME) ASC

这就产生了我想要的结果。但是,如何使用NSSortDescriptor在核心数据中实现这一点呢?

在创建模型之前,有人能提出一种根据结果集进行排序的方法吗?NSSortDescriptior将只允许我按实体的任何一个键进行排序。或者,除了根据NSDictionary结果进行排序之外,可能还有更有效的排序解决方案。结果集可以是1000行。谢谢

尝试使用方便的方法sortUsingComparator。。。

    [<<insert Array or Dictionary>> sortUsingComparator:^NSComparisonResult(ObjectA *objectA, ObjectB *objectB) {
        NSString *titleA = nil;
        NSString *titleB = nil;
        titleA = [objectA valueForKey:@"titleForObjectA"];
        titleB = [objectB valueForKey:@"titleForObjectB"];
        return [titleA localizedStandardCompare:titleB];
    }];

更新:很抱歉,这是NSMutableArray的一个方便方法。

尽管对于NSDictionary。。。

keysSortedByValueUsingComparator文档,所以也许你可以在这个方便的方法中添加一个类似于上面的比较器块?

最新更新