2013-03-28 42 views
1

我有一个核心数据结构就像如下:获取独特的核心数据实体@Max谓词

+-------+-----+---------+ 
| uid | id | category 
+-------+-----+---------+ 
| 12345 | 1 | 1 
| 23456 | 1 | 1 
| 34567 | 2 | 1 
| 45678 | 2 | 2 
| 56789 | 2 | 2 
+-------+-----+---------+ 

是否可以查询数据,使得我返回NSManagedObjects(非字典)具有独特的ID /类别组合?使用上面的示例表,我想有一个包含具有以下uid的对象的数组:23456(id-1 category-1的最大uid),34567(id-2 category-1的max uid),56789(最大UID为ID-2类-2)

有了原始的SQL我可以用下面这样做:

SELECT MAX(uid), id, category FROM TABLE GROUP BY id, category 

是否可以翻译上面的SQL到NSFetchRequest?

+2

你有看看http://stackoverflow.com/questions/3197141/core-data-predicate-with-group-and-max? –

回答

0

鉴于其他答案(比如Martin R指出的),我把它分成了两部分。首先,使用与NSDictionaryResultType为获取请求得到所有的最大的uid:

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:context]; 
[request setEntity:entity]; 

NSExpression *expr = [NSExpression expressionForKeyPath:@"uid"]; 
NSExpression *maxExpr = [NSExpression expressionForFunction:@"max:" arguments:@[expr]]; 
NSExpressionDescription *exprDesc = [[NSExpressionDescription alloc] init]; 
[exprDesc setExpression:maxExpr]; 
[exprDesc setName:@"uid"]; 

NSPropertyDescription *id = [[entity propertiesByName] objectForKey:@"id"]; 
NSPropertyDescription *cat = [[entity propertiesByName] objectForKey:@"category"]; 

[request setPropertiesToGroupBy:[NSArray arrayWithObjects:id, cat, nil]]; 
[request setPropertiesToFetch:[NSArray arrayWithObjects:exprDesc, nil]]; 
[request setResultType:NSDictionaryResultType]; 

NSArray *result = [context executeFetchRequest:request error:nil]; 
NSArray *maxUids = [result valueForKeyPath:@"uid"]; 

其次,使用maxUids阵列使用下面的谓词来获取相应的NSManagedObjects:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(uid IN %@)", maxUids]; 

使用两个取请求并不理想,但提供了使用SUBQUERY和/或更改底层数据模型的替代方法。