本文介绍了coredata中列的所有值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图设置我的NSFetchRequest核心数据检索列的所有值的总和。我的学生记录是以下格式 name | id |标记| _______ | _____ | _________ | Jack | 12 | 34 | John | 13 | 27 | Jeff | 1 | 42 | Don | 34 | 32 | Edward | 43 | 35 | Ricky | 23 | 24 | 任何人都建议我设置一个NSFetchRequest,返回记录中所有标记的总和 解决方案 c> NSManagedObjectContext * context = ...你的上下文; NSFetchRequest * request = [[NSFetchRequest alloc] init]; NSEntityDescription * entity = [NSEntityDescription entityForName:@Student inManagedObjectContext:context]; [request setEntity:entity]; //指定请求应该返回字典。 [request setResultType:NSDictionaryResultType]; //为键路径创建一个表达式。 NSExpression * keyPathExpression = [NSExpression expressionForKeyPath:@marks]; //创建表示标记总和的表达式 NSExpression * maxExpression = [NSExpression expressionForFunction:@sum: arguments:@ [keyPathExpression]]; NSExpressionDescription * expressionDescription = [[NSExpressionDescription alloc] init]; [expressionDescription setName:@markersSum]; [expressionDescription setExpression:maxExpression]; [expressionDescription setExpressionResultType:NSInteger32AttributeType]; //设置请求的属性以仅获取表达式表示的属性。 [request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]]; //执行提取。 NSError * error = nil; NSArray * result = [context executeFetchRequest:request error:& error]; NSLog(@%@,result); 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 解决方案 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 marksNSExpression *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中列的所有值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-13 19:00