错误计算的总和expressionForKeyPath sum:核心数据

时间:2015-05-16 17:54:53

标签: objective-c math core-data expression

可能我做错了什么?

所以,我很少有实体有关系 “Shop-> amountIncome和 - > amountExpense”

我正在努力计算总收入和支出。 我有动态tabelView

我从

开始
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

和一些搜索

Shop *shop = nil;
if (self.searchPredicate == nil) {
    shop = [self.fetchedResultsController objectAtIndexPath:indexPath];
}
else {
    shop = [self.fetchedResultsController.fetchedObjects filteredArrayUsingPredicate:self.
            searchPredicate][indexPath.row];
}

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.textLabel.text = shop.shopName;

所以我从我的实体“Shop”的请求开始(它有关系 - > amountIncome和 - > amountExpense

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Shop"
                                          inManagedObjectContext:[self managedObjectContext]];

[fetchRequest setEntity:entity];

我有几家商店,所以我按店名做了谓词

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"shopName = %@", shop.shopName]];
fetchRequest.resultType = NSDictionaryResultType;

毕竟我做了计算总和的东西:

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
expressionDescription.name = @"amountIncome";
expressionDescription.expression = [NSExpression expressionForKeyPath:@"@sum.incomes.amountIncome"];
expressionDescription.expressionResultType = NSDecimalAttributeType;

NSExpressionDescription *expressionDescriptionExpense = [[NSExpressionDescription alloc] init];
expressionDescriptionExpense.name = @"amountExpense";
expressionDescriptionExpense.expression = [NSExpression expressionForKeyPath:@"@sum.expenses.amountExpense"];
expressionDescriptionExpense.expressionResultType = NSDecimalAttributeType;

fetchRequest.propertiesToFetch = @[expressionDescription, expressionDescriptionExpense];

NSError *error = nil;
NSArray *result = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSLog(@"%@",result);

if (result == nil)
{
    NSLog(@"Error: %@", error);
}
else
{
    NSNumber *sumOfAmounts = [[result objectAtIndex:0] objectForKey:@"amountIncome"];
    NSNumber *sumOfAmountsExpense = [[result objectAtIndex:0] objectForKey:@"amountExpense"];

    NSString* amount = [NSString stringWithFormat:@"inc %@/ exp %@/ difference",
                        sumOfAmounts, sumOfAmountsExpense];

结果我想在detailTextLabel中显示

    cell.detailTextLabel.text = amount;
}
return cell;

事情是,那个数量收入计数正确,但是金额计算错误(如重复计算) 我错过了什么,我的错误是什么? 附:对不起我的英文;(

1 个答案:

答案 0 :(得分:1)

你试过KVC吗?

NSNumber *sumIncome = [allIncomes valueForKeyPath:@"@sum.amountIncome"];
NSNumber *sumExpense = [allExpenses valueForKeyPath:@"@sum.amountExpense"];