可能是我做错了吗?
因此,我只有几个实体具有“商店-> 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];
我有几家商店,所以我按shopName做谓语
[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计数错误(例如重复计数),我所缺少的是什么,我的错误是什么? PS对不起我的英语;(