First of all: Happy new year :-)
What I am trying to do
I am trying to divide two attributes in Core Data and then calculate the average of these divisions. The attributes are specified by a key path (e.g. eur
, usd
, aud
).
Example:
I have the following data set:
date eur usd aud
------------------------------
2010-01-01 0.5 1.0 1.5
2010-01-02 0.6 1.1 1.6
2010-01-03 0.4 1.0 1.3
Divide two attributes, e.g. eur / usd with the follwowing results...
divide eur / usd:
------------------
2010-01-01 0.5
2010-01-02 0.54
2010-01-03 0.4
... then calculate the average of these numbers (0.5 + 0.54 + 0.4)/3 = 0.48
My code
Since I would like to have these calculations performed directly by Core Data, I created the following expressions and fetch request:
NSExpression *fromCurrencyPathExpression = [NSExpression
expressionForKeyPath:fromCurrency.lowercaseString];
NSExpression *toCurrencyPathExpression = [NSExpression
expressionForKeyPath:toCurrency.lowercaseString];
NSExpression *divisionExpression = [NSExpression
expressionForFunction:@"divide:by:"
arguments:@[fromCurrencyPathExpression,
toCurrencyPathExpression]];
NSExpression *averageExpression = [NSExpression expressionForFunction:@"average:"
arguments:@[divisionExpression]];
NSString *expressionName = @"averageRate";
NSExpressionDescription *expressionDescription =
[[NSExpressionDescription alloc] init];
expressionDescription.name = expressionName;
expressionDescription.expression = averageExpression;
expressionDescription.expressionResultType= NSDoubleAttributeType;
NSFetchRequest *request = [NSFetchRequest
fetchRequestWithEntityName:NSStringFromClass([self class])];
NSPredicate *predicate =
[NSPredicate predicateWithFormat:@"date >= %@ AND date <= %@",startDate,fiscalPeriod.endDate];
request.predicate = predicate;
request.propertiesToFetch = @[expressionDescription];
request.resultType = NSDictionaryResultType;
NSError *error;
NSArray *results = [context
executeFetchRequest:request error:&error];
The problem
However, when running the app, it crashes with the error message:
Unsupported argument to sum : (
"eur / usd"
What is wrong with my code?
How can I chain the two calculations and have them performed directly in Core Data?
Thank you!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…