【问题标题】:Calculate Sum from Multiple Section Table using Core Data使用核心数据计算多节表的总和
【发布时间】:2015-07-04 05:26:10
【问题描述】:

我有一个 UITableView 有 2 个部分,每个部分获取已添加到 Core Data 的信息。每个部分都有一个称为数量的属性。我想得到每个部分的总和。

现在我的代码给了我所有值的总和。

如何修改它以通过每个部分?

我正在使用Integer 16 在两个部分之间添加值。

这是我的代码:

- (void)calculate {
    CoreDataStack *coreDataStack = [CoreDataStack defaultStack];

    NSManagedObjectContext *context = coreDataStack.managedObjectContext;

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntityName"];
    fetchRequest.resultType = NSDictionaryResultType;

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

    fetchRequest.propertiesToFetch = @[expressionDescription];

    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:fetchRequest error:&error];

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

解决方案:

我在我的代码中添加了一个 NSPredicate,并且能够获得我的 Integer 16 的某个值。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myInt16 == x"]; // x is the value I want to get to (in my case I have 0 and 1)
[fetchRequest setPredicate:predicate];

【问题讨论】:

  • 您可以发布该解决方案作为答案,并在几天后接受。

标签: ios objective-c uitableview core-data


【解决方案1】:

您可以通过使用NSFetchedResultController 来实现这一点,而无需NSExpression 的疯狂,并获得更好的CPU 和内存性能。

将获取的结果控制器的sectionNameKeyPath 设置为区分这两个部分的属性,我们称之为section(可能只包含01)。

然后,在表格视图的titleForHeaderInSection 中方便地计算总和。

id <NSFetchedResultsSectionInfo> info = 
   self.fetchedResultsController.sections[section];
NSNumber *sum = [info.objects valueForKeyPath:@"@sum.amount"];

【讨论】:

    【解决方案2】:

    您需要为您的获取请求设置propertiesToGroupBy

    fetchRequest.propertiesToFetch = @[@"myInt16", expressionDescription];
    fetchRequest.propertiesToGroupBy = @[@"myInt16"];
    

    获取将返回一个字典数组,每个字典都有两个键:“myInt16”和“sumOfAmount”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多