user684360
user684360

Reputation: 47

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.

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:@"[email protected]"] 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.

Upvotes: 2

Views: 1881

Answers (1)

salo.dm
salo.dm

Reputation: 2315

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.

Upvotes: 8

Related Questions