对Core Data属性/列执行基本计算

时间:2013-03-28 13:48:03

标签: ios objective-c sqlite core-data nsfetchrequest

我正在使用基于核心数据的时间序列(实体/表格),其中包含以下属性/列:

dateTime mc nd re

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

我尝试使用以下代码在数据库级别执行计算但在我的结果数组中得到错误的结果(每行多个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);

1 个答案:

答案 0 :(得分:2)

这似乎是Core Data中的一个错误。如果设置启动参数“-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];

它返回预期的结果。