我是第一次在这一轮发帖,所以如果我没有正确遵守所有规则,请多多包涵。
我正在为 iPhone (OS 3.1) 编写一个应用程序,并试图编写一些代码来添加小数。我有一个名为 SimpleItem 的核心数据实体,它有一个数量属性。这是我写的测试用例:
// Create and configure objects
SimpleItem *si1 = [self createSimpleItem:@"si1"];
si1.amount = [NSDecimalNumber decimalNumberWithMantissa:1000 exponent:0 isNegative:NO];
SimpleItem *si2 = [self createSimpleItem:@"s12"];
si2.amount = [NSDecimalNumber decimalNumberWithMantissa:2000 exponent:0 isNegative:NO];
// Need to save prior to fetching results with NSDictionaryResultType (known limitation)
[self save];
// Describe fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"SimpleItem" inManagedObjectContext:self.context];
[request setEntity:entityDescription];
[request setResultType:NSDictionaryResultType];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"amount"];
// For whatever reason, evaluating this expression here is absolutely not working. Probably decimals aren't handled properly.
NSExpression *sumAmountExpression = [NSExpression
expressionForFunction:@"max:"
arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"amount"];
[expressionDescription setExpression:sumAmountExpression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Fetch the amounts
NSError *error = nil;
NSArray *array = [self.context executeFetchRequest:request error:&error];
如果我通过 otest 执行此代码并对其进行调试,则在执行 fetch 请求时会出现异常:“-[NSDecimalNumber count]: unrecognized selector sent to instance.”
不过,仅在没有聚合函数的情况下评估 keyPathExpression 就可以正常工作。
参考文档显示了完全相同的示例,所以我想知道我做错了什么。或者这可能只是一个错误?
一切顺利,哈拉尔