0
我有名字FoodItem
一個實體,它有一個屬性,price
(雙)。理想情況下,此代碼的輸出將爲:計算所有NSManagedObjects'的平均屬性
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: %@", @"");
因此,我應該使用NSFetchedResultsController的唯一實時是如果數據將顯示在UITableView? – Skyler
是的。它也可以與'UICollectionView'(類似於一個表)一起使用。 –
這可能聽起來像一個愚蠢的問題,但如果我說,像以前一樣的屬性的平均值,託管對象仍然提取並存儲在NSArray *對象中呢?我將如何去訪問它們? – Skyler