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

Incorrectly calculated sum expressionForKeyPath sum: core data

可能是我做错了什么?

所以,我几乎没有关系的实体 "Shop->amountIncome and -> 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 和 ->花费金额

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];

以及我想详细显示的结果TextLabel

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

事实是,amountIncome 计算正确,但 amountExpense 计算错误(如重复计算) 我错过了什么,我的错误是什么? P.S。对不起我的英语;(

你试过KVC吗?

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