2012-02-06 34 views
7

當前使用核心數據。我有一個表,其中我試圖找回沿着這些線路的信息:通過核心數據區分計數,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(); 
} 

回答

14

這是可能的NSExpression爲您最初提出的,在我做作的例子中,我所謂的「人」的實體,一個名爲「EMAILADDRESS」屬性,我希望得到的計數。

NSPropertyDescription *propDesc = [[[[model entitiesByName] objectForKey:@"Person"] propertiesByName] objectForKey:@"emailAddress"]; 
NSExpression *emailExpr = [NSExpression expressionForKeyPath:@"emailAddress"]; 
NSExpression *countExpr = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:emailExpr]]; 
NSExpressionDescription *exprDesc = [[NSExpressionDescription alloc] init]; 
[exprDesc setExpression:countExpr]; 
[exprDesc setExpressionResultType:NSInteger64AttributeType]; 
[exprDesc setName:@"count"]; 

NSFetchRequest *fr = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; 
[fr setPropertiesToGroupBy:[NSArray arrayWithObject:propDesc]]; 
[fr setPropertiesToFetch:[NSArray arrayWithObjects:propDesc, exprDesc, nil]]; 
[fr setResultType:NSDictionaryResultType]; 
NSArray *results = [moc executeFetchRequest:fr error:&error]; 

我寫的代碼片段1000個記錄預填充數據庫:

NSArray *emailAddresses = [NSArray arrayWithObjects:@"[email protected]", @"[email protected]", @"[email protected]", @"[email protected]", @"[email protected]", nil]; 
    for (int i = 0; i < 1000; i++) { 
     NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:moc]; 
     [person setValue:[NSNumber numberWithInt:i] forKey:@"aNumber"]; 
     [person setValue:[[NSUUID UUID] UUIDString] forKey:@"aUUID"]; 
     [person setValue:[emailAddresses objectAtIndex:(i % [emailAddresses count])] forKey:@"emailAddress"]; 
    } 

將上面的代碼插入每個電子郵件地址200次,這裏的結果:

2012-05-31 15:17:42.160 Scratch[16084:10d03] CoreData: sql: SELECT t0.ZEMAILADDRESS, COUNT(t0.ZEMAILADDRESS) FROM ZPERSON t0 GROUP BY t0.ZEMAILADDRESS 
2012-05-31 15:17:42.162 Scratch[16084:10d03] CoreData: annotation: sql connection fetch time: 0.0024s 
2012-05-31 15:17:42.163 Scratch[16084:10d03] CoreData: annotation: total fetch execution time: 0.0029s for 5 rows. 
(gdb) po results 
(NSArray *) $2 = 0x0f811280 <_PFArray 0xf811280>(
{ 
    count = 200; 
    emailAddress = "[email protected]"; 
}, 
{ 
    count = 200; 
    emailAddress = "[email protected]"; 
}, 
{ 
    count = 200; 
    emailAddress = "[email protected]"; 
}, 
{ 
    count = 200; 
    emailAddress = "[email protected]"; 
}, 
{ 
    count = 200; 
    emailAddress = "[email protected]"; 
} 
) 
+1

我看到我錯過了NSPropertyDescription,它可以通過添加「Group By item」行來允許NSFetchRequest被正確解釋爲SQL查詢。發佈時我並不知道這個對象。我可以在二月份使用你的答案......哈哈。這是很好的知道,如果我決定在未來使用這種解決方案。感謝您的回覆。 :-) – 2012-07-29 15:18:43

+0

有一點需要注意,原作者提到使用NSFetchedResultsController進行分組。不幸的是,對於'setPropertiesToGroupBy'的工作,你需要'setResultType:NSDictionaryResultType'來禁用跟蹤修改。請參閱http://stackoverflow.com/a/4361198/287403 – 2014-02-21 22:14:49

+0

是否可以通過計數對所有這些進行排序? – Andy 2015-11-27 17:36:57

相關問題