问题描述
使用核心数据,我遇到了一个问题。我有一个实体 Movement,属性为 amount。如何计算所有实例的所有数量之和?我想了解如何使用 NSExpressionDescription
,但是 NSSet
就足够了。
Using Core Data, I encountered a problem. I have an entity "Movement" with an attribute "amount". How do I make the sum of all the "amount" of all instances? I'd like to understand how to use NSExpressionDescription
, but it's good enough NSSet
.
推荐答案
具有managedObjectContext:
Having a managedObjectContext:
NSManagedObjectContext *managedObjectContext = ...
我们使用返回类型字典创建获取请求:
We create a fetch request with return type dictionary:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Movement class])];
fetchRequest.resultType = NSDictionaryResultType;
然后我们创建一个表达式描述来计算总和:
Then we create an expression description to calculate the sum:
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
expressionDescription.name = @"sumOfAmounts";
expressionDescription.expression = [NSExpression expressionForKeyPath:@"@sum.amount"];
expressionDescription.expressionResultType = NSDecimalAttributeType;
设置请求属性以获取:
fetchRequest.propertiesToFetch = @[expressionDescription];
如果需要,我们还可以设置谓词。
We could also set a predicate if we want.
最后,我们执行请求,并得到一个包含一个带有一个键的字典的数组(@ sumOfAmounts),其值是一个带有数量总和的NSNumber。
And last we execute the request and get an array containing a dictionary with one key(@"sumOfAmounts") and its value is a NSNumber with the sum of amounts.
NSError *error = nil;
NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (result == nil)
{
NSLog(@"Error: %@", error);
}
else
{
NSNumber *sumOfAmounts = [[result objectAtIndex:0] objectForKey:@"sumOfAmounts"];
}
干杯
这篇关于所有实例的核心数据总和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!