coredata 中某一列的所有值的总和 [英] Sum of all values of a column in coredata

查看:23
本文介绍了coredata 中某一列的所有值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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   |

谁能建议我设置一个 NSFetchRequest 来返回记录中所有标记的总和

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

推荐答案

NSExpressions 会帮助你.

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

这篇关于coredata 中某一列的所有值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆