如何将零作为核心数据总和的默认值?

时间:2014-04-26 05:12:57

标签: ios objective-c core-data nsfetchrequest

我正在构建费用跟踪器应用以学习核心数据。我的费用被组织成类别,这些类别显示在主屏幕的集合视图中。每个单元格都有该类别的名称和其下的每日费用。

我的集合视图是可重新排序的,我可以在托管对象上下文中更改我的类别的顺序,但我不能对总计执行相同的操作。为了获得总数,我有NSFetchedResultsController这样构建:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:NSStringFromClass([SPRExpense class]) inManagedObjectContext:[SPRManagedDocument sharedDocument].managedObjectContext];
fetchRequest.entity = entityDescription;

NSDate *startDate, *endDate;

// Get the 00:00 and 23:59 of the current date here...

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dateSpent >= %@ AND dateSpent <= %@", startDate, endDate];
fetchRequest.predicate = predicate;

NSExpressionDescription *totalColumn = [[NSExpressionDescription alloc] init];
totalColumn.name = @"total";
totalColumn.expression = [NSExpression expressionWithFormat:@"@sum.amount"];
totalColumn.expressionResultType = NSDecimalAttributeType;

fetchRequest.propertiesToFetch = @[totalColumn];
fetchRequest.propertiesToGroupBy = @[@"category"];
fetchRequest.resultType = NSDictionaryResultType;

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"category.displayOrder" ascending:YES];
fetchRequest.sortDescriptors = @[sortDescriptor];

NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[SPRManagedDocument sharedDocument].managedObjectContext sectionNameKeyPath:nil cacheName:nil];

但是,当我执行fetchedResultsController.fetchedObjects时,它只会返回当天在其下列出费用的类别的总计。重新排序我的类别时出现问题,因为fetchedObjects计数与我的类别数量不同。

如果类别中没有任何可用的总和,我可以修改我的获取结果控制器以返回零作为总和吗?

0 个答案:

没有答案