3

在我的 ios 项目中,我使用了两个实体(CoreData):Person 和 Gifts with To-Many 关系

我知道如何计算给一个人的礼物总和:

NSDecimalNumber *orderSum=[person.gifts valueForKeyPath:@"@sum.priceOfGift"];

但是我如何计算所有人的总和?

 -(NSFetchedResultsController *) fetchedResultsController {
if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}
//NSError *error = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person"
                                          inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"nameOfPerson"
                                                               ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];


_fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"nameOfGroup" cacheName:nil];

_fetchedResultsController.delegate = self;

return _fetchedResultsController;

}

4

2 回答 2

2

“所有人的总和”将是获取所有人并计算他们

int sum = fetchedObjects.count;

但也许你的意思是“所有人所有礼物的价格总和”。仔细一想,这和所有礼物的价格总和是一样的。因此,您可以只取礼物并计算

NSNumber *sum = [self.fetchedResultsController.fetchedObjects 
      valueForKeyPath:@"@sum.priceOfGift"];
于 2012-12-20T10:34:25.073 回答
1

您可以尝试获取所有人员,然后使用总和

    NSError *error = nil;
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:managedObjectContext];
    request.predicate = nil;
    request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES]];//some parameter
    NSArray *persons =  [managedObjectContext executeFetchRequest:request error:&error];
 NSDecimalNumber *orderSum;
 for (Person *person in persons)
  orderSum = [NSDecimalNumber decimalNumberWithDecimal:orderSum.decimalValue
+[person valueForKeyPath:@"gifts.@sum.priceOfGift"].decimalValue]

不过,现在使用 NSDecimalNumber 看起来有点不舒服。

于 2012-12-19T21:50:16.797 回答