Eddy
Eddy

Reputation: 81

Save and retrieve data "by date" using Core Data

I'm trying to figure out how to save data "by date" in Core Data using Swift 2.0. In SQL I would want something like

select sum(amount) from X where date = 'date'

To accomplish this, I would need to

1. Record the time/date an item was added
2. Define some line of code that will function like the SQL statement above

I'm not sure how to do either of these. I've looked around online at Apple's documentation but didn't see anything. Can someone point me in the right direction?

Upvotes: 0

Views: 535

Answers (1)

bteapot
bteapot

Reputation: 2027

Use NSExpressionDescription:

NSExpressionDescription *sumAmountDescription = [[NSExpressionDescription alloc] init];
sumAmountDescription.name = @"sumAmount";
sumAmountDescription.expression = [NSExpression expressionForKeyPath:@"@sum.amount"];
sumAmountDescription.expressionResultType = NSInteger32AttributeType;

NSDate *date = <your date>;

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"<entity name here>"];
request.resultType = NSDictionaryResultType;
request.predicate = [NSPredicate predicateWithFormat:@"date == %@", date];
request.propertiesToFetch = @[sumAmountDescription];

NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];

NSDictionary *values = result.firstObject;
NSNumber *sumAmount = values[@"sumAmount"];

Upvotes: 1

Related Questions