所有实例属性的核心数据总和

Vin*_*ins 9 core-data ios

使用Core Data,我遇到了一个问题.我有一个实体"运动",其属性为"金额".如何计算所有实例的所有"金额"的总和?我想了解如何使用NSExpressionDescription,但它足够好NSSet.

e19*_*985 21

有一个managedObjectContext:

NSManagedObjectContext *managedObjectContext = ...
Run Code Online (Sandbox Code Playgroud)

我们使用返回类型字典创建一个获取请求:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Movement class])];
fetchRequest.resultType = NSDictionaryResultType;
Run Code Online (Sandbox Code Playgroud)

然后我们创建一个表达式描述来计算总和:

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
expressionDescription.name = @"sumOfAmounts";
expressionDescription.expression = [NSExpression expressionForKeyPath:@"@sum.amount"];
expressionDescription.expressionResultType = NSDecimalAttributeType;
Run Code Online (Sandbox Code Playgroud)

将请求属性设置为fetch:

fetchRequest.propertiesToFetch = @[expressionDescription];
Run Code Online (Sandbox Code Playgroud)

如果需要,我们也可以设置谓词.

最后我们执行请求并获取一个包含带有一个键的字典的数组(@"sumOfAmounts"),其值是一个带有金额总和的NSNumber.

NSError *error = nil;
NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (result == nil)
{
    NSLog(@"Error: %@", error);
}
else
{
    NSNumber *sumOfAmounts = [[result objectAtIndex:0] objectForKey:@"sumOfAmounts"];
}
Run Code Online (Sandbox Code Playgroud)

干杯


why*_*ite 9

这是一个使用和来汇总托管对象属性的Swift示例.该示例假定已命名托管对象,并且sum的属性为 .NSExpressionNSExpressionDescriptionMovementamount

例:

 func sumAmount() -> Double {
    var amountTotal : Double = 0

    // Step 1:
    // - Create the summing expression on the amount attribute.
    // - Name the expression result as 'amountTotal'.
    // - Assign the expression result data type as a Double.

    let expression = NSExpressionDescription()
    expression.expression =  NSExpression(forFunction: "sum:", arguments:[NSExpression(forKeyPath: "amount")])
    expression.name = "amountTotal";
    expression.expressionResultType = NSAttributeType.doubleAttributeType

    // Step 2:
    // - Create the fetch request for the Movement entity.
    // - Indicate that the fetched properties are those that were
    //   described in `expression`.
    // - Indicate that the result type is a dictionary.

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Movement")
    fetchRequest.propertiesToFetch = [expression]
    fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType

    // Step 3:
    // - Execute the fetch request which returns an array.
    // - There will only be one result. Get the first array
    //   element and assign to 'resultMap'.
    // - The summed amount value is in the dictionary as
    //   'amountTotal'. This will be summed value.

    do {
        let results = try context.fetch(fetchRequest)
        let resultMap = results[0] as! [String:Double]
        amountTotal = resultMap["amountTotal"]!
    } catch let error as NSError {
        NSLog("Error when summing amounts: \(error.localizedDescription)")
    }

    return amountTotal
}
Run Code Online (Sandbox Code Playgroud)

对步骤的补充讨论:

第1步 - 创建NSExpressionDescription变量.这NSExpressionDescription表明对参数应用了什么类型的函数.的总和函数被施加到属性.

expression.expression =  NSExpression(forFunction: "sum:", 
    arguments:[NSExpression(forKeyPath: "amount")])
Run Code Online (Sandbox Code Playgroud)

请注意,arguments参数是一个数组.您可以在数组中传递不同类型的表达式,但在我们的示例中,我们只需要该amount属性.

第2步 - 在此处建立获取请求.请注意,结果类型被指定为字典:fetchRequest.resultType = NSAttributeType.DictionaryResultType.在第3步中,我们将使用expression.nameamountTotal作为键来访问求和值.

第3步 - 我们执行获取请求并返回将是一个元素数组.该元素将是一个字典,我们可以[String:Double]:let resultMap = results[0] as! [String:Double].字典的值是Double,因为在第1步中我们指出它expression.expressionResultType是Double.

最后,我们通过调用与amountTotal键关联的字典值来访问总和:resultMap["amountTotal"]!


参考文献:

NSExpressionNSExpressionDescription