ios most efficient way to get average value while also filtering out some objects

会有一股神秘感。 提交于 2019-12-09 22:32:01

问题


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.

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>

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];

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.

Thanks for your help.


回答1:


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;
}

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"]; 

Note that this code hasn't been tested. You might also use NSDecimalAttributeType instead of the float type if you're working with NSDecimalNumbers.



来源:https://stackoverflow.com/questions/8142435/ios-most-efficient-way-to-get-average-value-while-also-filtering-out-some-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!