1

我正在使用基于核心数据的时间序列(实体/表),它由以下属性/列组成:

dateTime mc nd re

根据公式result = (mc + nd) / re,我想计算每一行的结果并在数组中返回结果(日期时间 + 值)。

我尝试使用以下代码在数据库级别执行计算,但在我的结果数组中确实得到了错误的结果(每行多个 dateTime 值,错误的计算结果)。但是,NSExpressionDescription在 NSLogging 时返回正确的公式。

您对我的代码可能有什么问题有任何想法吗?

NSString *divisorKeyPath = @"revenue"
NSExpression *marketCapExpression = [NSExpression expressionForKeyPath:@"mc"];
NSExpression *netDebtExpression   = [NSExpression expressionForKeyPath:@"nd"];
NSExpression *divisorExpression   = [NSExpression expressionForKeyPath:
    divisorKeyPath];
NSExpression *evExpression        = [NSExpression expressionForFunction:
    @"add:to:"  
    arguments:@[marketCapExpression,netDebtExpression]];
NSExpression *divisionExpression  = [NSExpression expressionForFunction:
    @"divide:by:"
    arguments:@[evExpression, divisorExpression]];
NSString *divisionExpressionName = @"division";
NSExpressionDescription *divisionDescription  = [[NSExpressionDescription alloc] init];
divisionDescription.name                      = divisionExpressionName;
divisionDescription.expression                = divisionExpression;
divisionDescription.expressionResultType      = NSDoubleAttributeType;

NSFetchRequest *divisionRequest = [NSFetchRequest fetchRequestWithEntityName:
   NSStringFromClass([SharePrice class])];
divisionRequest.propertiesToFetch = @[@"dateTime",divisionDescription];
divisionRequest.resultType = NSDictionaryResultType;
NSSortDescriptor *sortDescriptor = [NSSortDescriptor 
   sortDescriptorWithKey:@"dateTime" ascending:YES];
divisionRequest.sortDescriptors = @[sortDescriptor];

NSError *error;
NSArray *divisionResults = [self.managedDocument.managedObjectContext
   executeFetchRequest:divisionRequest error:&error];
NSLog(@"results: %@",divisionResults);
4

1 回答 1

2

这似乎是核心数据中的一个错误。如果您设置启动参数“-com.apple.CoreData.SQLDebug 3”,那么您可以看到表达式描述被转换为 SQLite 查询

SELECT t0.ZDATETIME,  t0.ZMARKETCAP +  t0.ZNETDEBT /  t0.ZREVENUE FROM ZENTITY t0 ORDER BY t0.ZDATETIME

并不是

SELECT t0.ZDATETIME,  (t0.ZMARKETCAP +  t0.ZNETDEBT) /  t0.ZREVENUE FROM ZENTITY t0 ORDER BY t0.ZDATETIME

应该是这样。

divisionExpression本身是正确的。如果将其应用于sharePrice实体的单个对象,请使用

NSNumber *x = [expression expressionValueWithObject:sharePrice context: nil];

它返回预期的结果。

于 2013-03-28T14:45:56.283 回答