Sum of all values of a column in coredata

2019-03-03 20:14发布

问题:

I am trying to setup my NSFetchRequest to core data to retrieve the sum of all values of a columns.My Student record is of the following format

 name  | id  |   marks |
_______|_____|_________|
Jack   |  12 |    34   |
John   |  13 |    27   |
Jeff   |   1 |    42   |
Don    |  34 |    32   |
Edward |  43 |    35   |
Ricky  |  23 |    24   |

Can any one suggest me to setup a NSFetchRequest which returns the sum of all marks in the record

回答1:

NSExpressions will help you.

NSManagedObjectContext *context = …your context;

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

// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];

// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"marks"];

// Create an expression to represent the sum of marks
NSExpression *maxExpression = [NSExpression expressionForFunction:@"sum:"
                                                        arguments:@[keyPathExpression]];

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"marksSum"];
[expressionDescription setExpression:maxExpression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];

// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

// Execute the fetch.
NSError *error = nil;
NSArray *result = [context executeFetchRequest:request error:&error];

NSLog(@"%@", result);


回答2:

Why NSExpression for a simple sum??

NSInteger sum = [allRecords valueForKeyPath:@"@sum.marks"].integerValue;


回答3:

You have to use CoreData agregate functions.

NSExpression *keyExpression = [NSExpression expressionForKeyPath:@"marks"];

//create the NSExpression to tell our NSExpressionDescription which calculation we are performing.
NSExpression *maxExpression = [NSExpression expressionForFunction:@"sum:" arguments:[NSArray arrayWithObject:keyExpression]];

NSExpressionDescription *description = [[NSExpressionDescription alloc] init];
[description setName:@"markSum"];
[description setExpression:maxExpression];
[description setExpressionResultType:NSInteger32AttributeType];

[request setPropertiesToFetch:[NSArray arrayWithObject:description]];

NSArray *results = [context executeFetchRequest:request error:&error];
if (results != nil && results.count > 0){
    NSNumber *markSum = [[results objectAtIndex:0] valueForKey:@"markSum"];
    NSLog(@"Sum: %@", markSum);
}