我有一个应用程序,可以随时显示商店的销售量。
NSNumber *amount = [self valueForKeyPath:@"sales.@sum.value"];现在,我必须过滤并按期间显示金额。我有一个字段"period“(字符串),它包含月份和年份,比如"2012-11”。
如何使用where子句执行相同的查询?
发布于 2013-01-15 02:44:29
您可以在计算总和之前过滤销售额。
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"];但是,对于每个销售,您仍然可以获得几个分配(托管对象、其缓存、其属性)。最好的解决方案是使用fetch请求在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"];https://stackoverflow.com/questions/14323291
复制相似问题