ios最有效的方式来获得平均值,同时也过滤掉一些对象 [英] ios most efficient way to get average value while also filtering out some objects
问题描述
我试图获取子实体中的属性的平均值,同时也只尝试包含一组选定的记录。
I'm trying to get the average value of an attribute in a child entity while also trying to only include a select set of records.
我有两个实体在我的核心数据模型中:Invoice和InvoiceDetail。
I have two entities in my Core Data model: Invoice and InvoiceDetail.
Invoice:<br>
invoiceNum - attribute<br>
invoiceDate - attribute<br>
invoiceDetails - one-to-many relationship to InvoiceDetail
InvoiceDetail:<br>
itemAmount - attribute<br>
itemType - attribute<br>
invoice - one-to-one relationship to Invoice<br>
如果我想获得整个发票的itemAmount的平均值, (invoice是一个NSManagedObject):
If I wanted to just get the average value of itemAmount for an entire invoice, I would use the following (invoice is an NSManagedObject):
float avgAmount = [[invoice valueForKeyPath:@"invoiceDetails.@avg.itemAmount"] floatValue];
但是,我只想获取itemType = 1的对象的平均值。通过invoiceDetail项目并手动执行此操作,但我知道这将导致性能问题。我不知道这是最好的方式。
However, I'm trying to only get the average for objects where itemType = 1. I can loop through the invoiceDetail items and do this manually, but I know that this will cause a performance issue. I'm not sure what is the best way to go about doing this.
感谢您的帮助。
推荐答案
您可以使用包含表达式的抓取请求来执行此操作,如下所示:
You can do it with a fetch request that contains an expression, as follows:
- (NSDictionary *)myFetchResults
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"InvoiceDetail" inManagedObjectContext:myContext];
request.predicate = [NSPredicate predicateWithFormat:@"itemType = %@", [NSNumber numberWithInt:1]];
request.resultType = NSDictionaryResultType;
NSExpressionDescription *aveExDescr = [[NSExpressionDescription alloc] init];
[aveExDescr setName:@"myAverage"];
[aveExDescr setExpression:[NSExpression expressionForFunction:@"average:"
arguments:[NSArray arrayWithObject:
[NSExpression expressionForKeyPath:@"itemAmount"]]]];
[aveExDescr setExpressionResultType:NSFloatAttributeType];
request.propertiesToFetch = [NSArray arrayWithObject:aveExDescr];
NSError *err = nil;
NSArray *results = [self.moContext executeFetchRequest:request error:&err];
[request release];
[err release];
return results;
}
fetch将返回一个字典,您可以访问如下: p>
The fetch will return a dictionary, which you can access as follows:
NSArray *results = [self myFetchResults];
NSDictionary *resultsDictionary = [results lastObject];
NSNumber *average = [resultsDictionary objectForKey:@"myAverage"];
请注意,此代码尚未经过测试。如果你使用NSDecimalNumbers,你也可以使用 NSDecimalAttributeType
而不是float类型。
Note that this code hasn't been tested. You might also use NSDecimalAttributeType
instead of the float type if you're working with NSDecimalNumbers.
这篇关于ios最有效的方式来获得平均值,同时也过滤掉一些对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!