Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

objective c - Chained expressions to perform calculations in Core Data

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems that "collection" function expressions like @average can only be used with key paths, but not in combination with other general expressions, when used as propertiesToFetch. I do not have a reference for that, but it is a problem that others have noticed also:

So you could proceed in two steps: First execute a fetch request that returns an array with the results of all divisions:

NSExpression *fromCurrencyPathExpression = [NSExpression
                                            expressionForKeyPath:@"eur"];
NSExpression *toCurrencyPathExpression   = [NSExpression
                                            expressionForKeyPath:@"usd"];
NSExpression *divisionExpression = [NSExpression
                                    expressionForFunction:@"divide:by:"
                                    arguments:@[fromCurrencyPathExpression,
                                    toCurrencyPathExpression]];

NSString *expressionName = @"ratio";
NSExpressionDescription *expressionDescription =
[[NSExpressionDescription alloc] init];
expressionDescription.name = expressionName;
expressionDescription.expression = divisionExpression;
expressionDescription.expressionResultType= NSDoubleAttributeType;

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];

request.propertiesToFetch = @[expressionDescription];
request.resultType = NSDictionaryResultType;

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

The result is an array of dictionaries:

(lldb) po ratios
(NSArray *) $0 = 0x00000001001170f0 <_PFArray 0x1001170f0>(
{
    ratio = "0.5454545454545454";
},
{
    ratio = "0.4";
},
{
    ratio = "0.5";
}
)

Also, with the "-com.apple.CoreData.SQLDebug 1" option one can see that the divisions are already executed on the SQLite level:

sql: SELECT  t0.ZEUR /  t0.ZUSD FROM ZENTITY t0

Then you can compute the average of all ratios in memory, using Key-Value Coding:

NSNumber *average = [ratios valueForKeyPath:@"@avg.ratio"];

and the result is

(lldb) po average
(NSNumber *) $0 = 0x000000010012fd60 0.4818181818181818

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...