我有一个名为 的实体FoodItem
,它有一个属性price
(双属性)。理想情况下,此代码的输出将是:
Average Price is: 6.00
虽然我不确定如何访问值 6.00。任何人都可以帮助我吗?谢谢
这是我的代码:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"FoodItem" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *o1 = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:self.managedObjectContext];
[o1 setValue:@(5.00) forKey:@"price"];
NSManagedObject *o2 = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:self.managedObjectContext];
[o2 setValue:@(7.00) forKey:@"price"];
[self.managedObjectContext save:nil];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setSortDescriptors:@[]];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"price"];
NSExpression *averagePriceExpression = [NSExpression expressionForFunction:@"average:"
arguments:@[keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"averagePrice"];
[expressionDescription setExpression:averagePriceExpression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
[controller performFetch:nil];
NSLog(@"Average price is: %@", @"");