The main amount of data for all instance attributes

Using Core Data , I ran into a problem. I have a Motion entity with a Sum attribute. How can I make the sum of all the "sums" of all copies? I would like to understand how to use NSExpressionDescription, but it is good enough NSSet.

+9
source share
3 answers

Availability of managed objects:

NSManagedObjectContext *managedObjectContext = ...

We create a query using a dictionary of type return:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Movement class])];
fetchRequest.resultType = NSDictionaryResultType;

Then we create a description of the expression to calculate the sum:

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
expressionDescription.name = @"sumOfAmounts";
expressionDescription.expression = [NSExpression expressionForKeyPath:@"@sum.amount"];
expressionDescription.expressionResultType = NSDecimalAttributeType;

Set the query properties to retrieve:

fetchRequest.propertiesToFetch = @[expressionDescription];

We can also set the predicate if we want.

, (@ "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"];
}

+20

Swift NSExpression NSExpressionDescription. , " Movement - amount.

:

 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
}

:

1 - NSExpressionDescription. NSExpressionDescription , . .

expression.expression =  NSExpression(forFunction: "sum:", 
    arguments:[NSExpression(forKeyPath: "amount")])

, arguments . , amount.

2 - . , : fetchRequest.resultType = NSAttributeType.DictionaryResultType. 3 expression.name amountTotal .

3 - , . , [String:Double]: let resultMap = results[0] as! [String:Double] let resultMap = results[0] as! [String:Double]. Double, 1 , expression.expressionResultType Double.

, , , amountTotal : resultMap["amountTotal"]!


:

NSExpression NSExpressionDescription

+7

The best way is to use a selection for certain values and provide an NSExpressionDescription with a function sum:.

When you select, you get an array of one element containing a dictionary whose keys correspond to the descriptions of the expressions and whose values ​​are the results of the expressions. In this case, you will receive a key sumwhose value will be the sum of the attributes provided to the expression.

+2
source

All Articles