Sum of all values of a column in coredata
我正在尝试将我的NSFetchRequest设置为核心数据以检索列的所有值的总和。我的学生记录具有以下格式
1 2 3 4 5 6 7 8 | name | id | marks | _______|_____|_________| Jack | 12 | 34 | John | 13 | 27 | Jeff | 1 | 42 | Don | 34 | 32 | Edward | 43 | 35 | Ricky | 23 | 24 | |
有人可以建议我设置NSFetchRequest,该记录返回记录中所有标记的总和吗?
表达式会帮助您。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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 | NSInteger sum = [allRecords valueForKeyPath:@"@sum.marks"].integerValue; |
您必须使用CoreData聚合函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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); } |