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...
Fetching Data From CoreData We have created a function fetch() whose return type is array of College(Entity). For fetching the data we just write context. fetch and pass fetchRequest that will generate an exception so we handle it by writing try catch, so we fetched our all the data from CoreData.
Core Data is a framework that you use to manage the model layer objects in your application. It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.
Overview. Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With