I have a view where I would like to get an average value of a "percentage" property without loading all the objects (and their other properties) into memory from Core Data. I have found out how to do this in Apple's docs, but the problem is I would like to limit the objects whose percentages are being averaged to ones that have another property called "numberAsked" greater than 0. I thought this was something I could do with an NSPredicate.
Here is what I have:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Statistics" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"numberAsked > 0"];
[request setPredicate:searchPredicate];
[request setResultType:NSDictionaryResultType];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"percentCorrect"];
NSExpression *averagePercentExpression = [NSExpression expressionForFunction:@"average:"
arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"averagePercentageCorrect"];
[expressionDescription setExpression:averagePercentExpression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
What happens is that it seems to fetch all objects and ignore the NSPredicate. I don't know if changing the request's result type does something to this, or I need to filter the objects with another NSExpression, or what.
My testing values are that right now all objects have the numberAsked property set to 0, so theoretically my final objects array should have a count of 0, from where I would specify "N/A" for the percentage. But that is not happening.
I appreciate any help!