In my ios project I use two entities (CoreData): Person and Gifts with To-Many Relationship

I know how to calculate the sum of gifts to one person:

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

But how do I calculate the sum of all persons?

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

}

有帮助吗?

解决方案

The "sum of all persons" would be to fetch all persons and count them

int sum = fetchedObjects.count;

But perhaps you mean the "sum of the prices of all gifts of all persons". If you think about it, it is the same as the sum of the prices of all gifts. Thus, you can just fetch the gifts and calculate

NSNumber *sum = [self.fetchedResultsController.fetchedObjects 
      valueForKeyPath:@"@sum.priceOfGift"];

其他提示

You can try to fetch all the Persons, then use the sum

    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]

Though, now work with NSDecimalNumber look a bit uncomfortable.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top