简体   繁体   中英

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?

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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM