當前使用核心數據。我有一個表,其中我試圖找回沿着這些線路的信息:通過核心數據區分計數,NSExpression進入NSFetchedResultsController
SELECT item, COUNT(*) FROM myTable GROUP BY item;
爲了生產這種類型的結果:
+---------+------+-------+
| item | COUNT(*) |
+---------+------+-------+
| group 1 | 2 |
| group 2 | 5 |
| group 3 | 8 |
+---------+------+-------+
我有好主意使用的NSExpression ,希望核心數據爲我做所有的工作。我開始旋轉我的輪子。 count:表達式函數正在崩潰。例外情況不是很清楚。使用其他表達式函數,如sum:不會使應用程序崩潰。
將結果存儲在NSFetchedResultsController將是不錯的。我已經探索過其他選擇,其中沒有一個不太吸引人。編寫一個SQL查詢並將其結合使用會更有意義,而不是在這種情況下使用Core Data作爲SQL包裝器?
供參考源代碼如下。
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"item"];
NSExpression *totalExpression = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription * totalExpressionDescription = [[NSExpressionDescription alloc] init];
[totalExpressionDescription setExpression:totalExpression];
[totalExpressionDescription setExpressionResultType:NSInteger64AttributeType];
[totalExpressionDescription setName:@"totalInstances"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"myEntity" inManagedObjectContext:self.managedObjectContext];
NSArray *propertiesToFetch = [[NSArray alloc] initWithObjects:strFieldName, totalExpressionDescription, nil];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setPropertiesToFetch:propertiesToFetch];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:strFieldName ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController* aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:nil];
...
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
我看到我錯過了NSPropertyDescription,它可以通過添加「Group By item」行來允許NSFetchRequest被正確解釋爲SQL查詢。發佈時我並不知道這個對象。我可以在二月份使用你的答案......哈哈。這是很好的知道,如果我決定在未來使用這種解決方案。感謝您的回覆。 :-) – 2012-07-29 15:18:43
有一點需要注意,原作者提到使用NSFetchedResultsController進行分組。不幸的是,對於'setPropertiesToGroupBy'的工作,你需要'setResultType:NSDictionaryResultType'來禁用跟蹤修改。請參閱http://stackoverflow.com/a/4361198/287403 – 2014-02-21 22:14:49
是否可以通過計數對所有這些進行排序? – Andy 2015-11-27 17:36:57