Jef*_*eff 1 sum core-data objective-c ios
我正在尝试将我的 NSFetchRequest 设置为核心数据以检索列的所有值的总和。我的学生记录采用以下格式
name | id | marks |
_______|_____|_________|
Jack | 12 | 34 |
John | 13 | 27 |
Jeff | 1 | 42 |
Don | 34 | 32 |
Edward | 43 | 35 |
Ricky | 23 | 24 |
Run Code Online (Sandbox Code Playgroud)
任何人都可以建议我设置一个 NSFetchRequest 来返回记录中所有标记的总和
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1949 次 |
| 最近记录: |