计算所有NSManagedObjects属性的平均值

时间:2013-06-25 20:31:57

标签: ios objective-c core-data nsexpression

我有一个名为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: %@", @"");

1 个答案:

答案 0 :(得分:2)

我不明白你为什么要使用获取结果控制器。此处不使用NSFetchedResultsController。请使用简单的NSFetchRequest

// Your previous code here

// Execute the fetch.
NSError *error = nil;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
    // Handle the error.
}
else {
    if ([objects count] > 0) {
        NSLog(@"Average price is: %@", [[objects objectAtIndex:0] valueForKey:@"averagePrice"]);
    }
}

可以从Apple doc Fetching Specific Values找到一个简单的例子。