2013-01-14 46 views

回答

2

可以計算總和前過濾銷售。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"period == %@", @"2012-11"]; 
NSSet *sales = [self valueForKeyPath:@"sales"]; 
NSSet *filteredSales = [sales filteredSetUsingPredicate:predicate]; 
NSNumber *amount = [filteredSales valueForKeyPath:@"@sum.value"]; 

但是,當你有很多幾十個或更多的銷售,這種方法,因爲它要求每個銷售加載到內存中是不是真的有效。

而且,如果銷售是過錯的,各自出售將fire a fault並生成SQL請求。在過濾它們之前,您可以通過batch faulting阻止此銷售。

我們將假設self是一個託管對象。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"period == %@", @"2012-11"]; 
NSSet *sales = [self valueForKeyPath:@"sales"]; 
// Begin batch-faulting 
NSManagedObjectContext *moc = [self managedObjectContext]; 
NSFetchRequest *request = [NSFetchRequest new]; 
[request setEntity:[NSEntityDescription entityForName:@"Sale" inManagedObjectContext:moc]]; 
[request setPredicate:[NSPredicate predicateWithFormat:@"self IN %@", sales]]; 
[request setReturnsObjectsAsFaults:NO]; 
[moc executeFetchRequest:request error:NULL]; 
// Batch-faulting done 
NSSet *filteredSales = [sales filteredSetUsingPredicate:predicate]; 
NSNumber *amount = [filteredSales valueForKeyPath:@"@sum.value"]; 

但是,你仍然可以爲每個銷售(被管理的對象,它的緩存,它的屬性)數分配。最好的解決方案是使用提取請求來計算SQLite數據庫中的總和。

NSString *reverseRelationship = @"store"; // name of the relationship from the sale to self 
NSExpressionDescription *description = [NSExpressionDescription new]; 
[description setName:@"amount"]; 
[description setExpressionResultType:NSDoubleAttributeType]; 
[description setExpression:[NSExpression expressionWithFormat:@"@sum.value"]]; 
NSManagedObjectContext *moc = [self managedObjectContext]; 
NSFetchRequest *request = [NSFetchRequest new]; 
[request setEntity:[NSEntityDescription entityForName:@"Sale" inManagedObjectContext:moc]]; 
[request setResultType:NSDictionaryResultType]; 
[request setPredicate:[NSPredicate predicateWithFormat: 
         @"%K == %@ AND period == %@", reverseRelationship, self, @"2012-11"]]; 
[request setPropertiesToFetch:@[description]]; 
NSDictionary *result = [[moc executeFetchRequest:request error:NULL] lastObject]; 
NSNumber *amount = [result objectForKey:@"amount"]; 
+0

不錯的答案。最後一個解決方案中的「測試」可能是'self'? –

+0

它的工作原理!謝謝! – franciscomxs

+0

@MartinR是的,謝謝。我編輯了答案。 –