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

给你一囗甜甜゛ 提交于 2019-12-04 16:55:37

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.

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