Counting distinct results
I have this request that allows me to retrieve distinct values over a combination of 4 different fields, and it works fine
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
[request setReturnsDistinctResults:YES];
[request setResultType:NSDictionaryResult开发者_开发技巧Type];
NSDictionary *entityProperties = [entity propertiesByName];
NSMutableArray *properties = [NSMutableArray arrayWithObject:[entityProperties objectForKey:@"A"]];
[properties addObject:[entityProperties objectForKey:@"B"]];
[properties addObject:[entityProperties objectForKey:@"C"]];
[properties addObject:[entityProperties objectForKey:@"D"]];
//[properties addObject:countExpressionDescription];
[request setPropertiesToFetch: properties];
Now i would like to add a field that counts the number of elements that have been grouped (before the distinct). I've tried to make that work with the following, but its not working :
NSExpression *kpe1 = [NSExpression expressionForKeyPath:@"A"];
NSExpression *kpe2 = [NSExpression expressionForKeyPath:@"B"];
NSExpression *kpe3 = [NSExpression expressionForKeyPath:@"C"];
NSExpression *kpe4 = [NSExpression expressionForKeyPath:@"D"];
NSMutableArray *keyPathExpressions = [NSMutableArray arrayWithObject:kpe1];
[keyPathExpressions addObject:kpe2];
[keyPathExpressions addObject:kpe3];
[keyPathExpressions addObject:kpe4];
NSExpression *countForFields = [NSExpression expressionForFunction:@"count:" arguments:keyPathExpressions];
NSExpressionDescription *countExpressionDescription = [[NSExpressionDescription alloc] init];
[countExpressionDescription setName:@"countID"];
[countExpressionDescription setExpression:countForFields];
[countExpressionDescription setExpressionResultType:NSInteger64AttributeType];
Im not even sure if it could work, do you have any ideas ?
Many thanks
精彩评论