Jim
Jim

Reputation: 9234

iPhone: Core Data, How to get sum of values from db

I have a model 'Pens' and it has such properties: "makerName" and "Count". How can I get sum of all 'Count' ? Can Core Data count that for me ? Thanks...

Upvotes: 5

Views: 4331

Answers (3)

MadhavanRP
MadhavanRP

Reputation: 2830

Yes, you can get those from core data, rather than fetching and evaluating the results. You can perform functions such as sum on the core data by use of NSExpression.

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"Count"];
NSExpression *sumOfCountExpression = [NSExpression expressionForFunction:@"sum:"
                                              arguments:[NSArray arrayWithObject:keyPathExpression]];

For a list of functions that you can use go here

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSExpression_Class/Reference/NSExpression.html.

You then need to create an NSExpressionDescription object where you set the expression tho the sumOfCountExpression that you just created.

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"sumOfCount"];
[expressionDescription setExpression:sumOfCountExpression];
[expressionDescription setExpressionResultType:NSDoubleAttributeType];

Then construct your requests as you would usually and then set the property to fetch to that expression.

[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

Refer: Core Data Programming Guide

Upvotes: 10

Scott
Scott

Reputation: 17037

I'm assuming the SQL equivalent you want is:

select sum(p.count) 
from pens p 
where makerName = '{whatever maker you are querying for}'

Take a look at this post for the code you're looking for.

Upvotes: 0

Tomasz Wojtkowiak
Tomasz Wojtkowiak

Reputation: 4920

There are two ways to solve this problem:
first - get your data to NSSet or NSArray and use @sum operator:

//assume that `pens` are NSArray of Pen
NSNumber *countSum=[pens valueForKeyPath:"@sum.count"];

second is using specific fetch for specific value with added NSExpressionDescription with a sum. This way is harder but better for larger db's

Upvotes: 9

Related Questions