我有一个拥有头衔和金额的实体。我想显示我实体中每个标题的总价值。
答案 0 :(得分:2)
通过利用KVC(键值编码),您几乎可以省去获取请求。
首次使用此谓词获取(或过滤):
[NSPredicate predicateWithFormat:@"category = %@", @"Food"];
然后将结果汇总到一行:
NSNumber *sum = [result valueForKeyPath:@"@sum.amount"];
无需仅使用NSDictionaryResultType
获取某些属性 - 只需获取正常的NSManagedObject
(核心数据将为您优化)。
答案 1 :(得分:0)
您使用NSPredicate按类别过滤对象,然后您只能获取某个属性的值,例如:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
// Entity
NSEntityDescription *ent = [NSEntityDescription entityForName:@"Incoming" inManagedObjectContext:context];
[request setEntity:ent];
// Predicate
NSPredicate *pred = [NSPredicate predicateWithFormat:@"category MATCHES[cd] %@", @"FOOD"];
[request setPredicate:pred];
// Property fetch
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:NO];
[request setPropertiesToFetch:@[@"Amount"]];
// Execute the fetch.
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
int total = 0;
if (objects) {
for(NSDictionary *dict in objects) {
NSString *key = dict.allKeys.lastObject;
total += [dict[key] intValue];
}
} else {
NSLog(@"Fetch error: %@", error.localizedDescription);
}
NSLog(@"Total: %i", total);
答案 2 :(得分:0)
以下内容将在一次获取操作中获取类别和总和:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Incoming"];
fetchRequest.resultType = NSDictionaryResultType;
NSExpression *sumExp = [NSExpression expressionWithFormat:@"sum:(amount)"];
NSExpressionDescription *sumED = [[NSExpressionDescription alloc] init];
sumED.name = @"sum";
sumED.expression = sumExp;
sumED.expressionResultType = NSDoubleAttributeType;
fetchRequest.propertiesToFetch = [@"title", sumED];
fetchRequest.propertiesToGroupBy = [@"title"];
NSArray *dictionaries = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
请参阅NSExpression
文档here。