将核心数据计算为多种关系

时间:2015-04-06 07:27:05

标签: objective-c core-data

我试图按照核心数据中的聚合函数进行排序。我的模型中有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行。谢谢!

1 个答案:

答案 0 :(得分:0)

尝试使用便捷方法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文档here,那么您是否可以在此便捷方法中添加与上述类似的比较器块?