保存并检索数据"按日期"使用核心数据

时间:2015-12-22 21:10:40

标签: ios swift core-data

我试图找出如何保存数据"按日期"在使用Swift 2.0的Core Data中。在SQL中我想要像

这样的东西

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

要做到这一点,我需要

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

我不确定如何做其中任何一项。我在网上查看了Apple的文档,但没有看到任何内容。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

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