2015-04-06 91 views
0

我想按核心數據中的聚合函數進行排序。我有一個模型,實體食譜和食物,他們之間有多對多的關係。我從列出包含我列出的食物的食譜的查詢開始。到目前爲止我有:將核心數據計數到很多關係

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行。謝謝!

回答

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,所以也許你可以添加類似上面的這個便捷方法比較塊?

+0

這是我使用的方法,它有一個缺點,即只在內存中對內容進行排序,儘管可以通過批量排序來提高性能。排序在sqlite查詢本身會更好。 – 2015-04-09 07:41:28