coredata中列的所有值的总和

时间:2014-03-14 07:15:04

标签: ios objective-c core-data sum

我正在尝试将NSFetchRequest设置为核心数据以检索列的所有值的总和。我的学生记录具有以下格式

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

任何人都可以建议我设置一个NSFetchRequest,它返回记录中所有标记的总和

3 个答案:

答案 0 :(得分:4)

NSExpressions会帮助你。

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);

答案 1 :(得分:3)

为什么NSExpression为简单的总和?

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

答案 2 :(得分:0)

您必须使用Core Data聚合函数。

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);
}