2013-06-25 67 views
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: %@", @""); 

回答

2

我不明白爲什麼你用一個獲取結果控制器這個。 A 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文檔Fetching Specific Values中找到。

+0

因此,我應該使用NSFetchedResultsController的唯一實時是如果數據將顯示在UITableView? – Skyler

+1

是的。它也可以與'UICollectionView'(類似於一個表)一起使用。 –

+0

這可能聽起來像一個愚蠢的問題,但如果我說,像以前一樣的屬性的平均值,託管對象仍然提取並存儲在NSArray *對象中呢?我將如何去訪問它們? – Skyler