2012-02-06 33 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

相关问题