在我的ios项目中,我使用了两个实体( CoreData ):具有多对多关系的人和礼物
我知道如何计算一个人的礼物总数:
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;
}
答案 0 :(得分:2)
所有人的总和"将是取所有人并计算他们
int sum = fetchedObjects.count;
但也许你的意思是所有人的所有礼物价格的总和"。如果您考虑一下,它与所有礼品的价格总和相同。因此,您只需获取礼物并计算
即可NSNumber *sum = [self.fetchedResultsController.fetchedObjects
valueForKeyPath:@"@sum.priceOfGift"];
答案 1 :(得分: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看起来有点不舒服。