Search code examples
objective-ccore-datansexpression

nsexpression with custom function core data


i'm trying to group and count on date on a core data entity. since date cant be group due to different time. so i'm trying to pass custom function to nsexpression. but i get some errors i dont know what's the correct way to do it.

code for grouping and counting:

NSEntityDescription *entity     = [NSEntityDescription entityForName:@"TEvents"
                                              inManagedObjectContext:context];
NSDictionary *props = [entity propertiesByName];

NSPropertyDescription *propDesc3 = [props objectForKey:@"startDateTime"];
NSExpression *propExpr3 = [NSExpression expressionForKeyPath:@"startDateTime"];
NSExpression *countExpr3 = [NSExpression expressionForFunction:propExpr3 selectorName:@"dateShort" arguments:nil];
NSExpressionDescription *exprDesc3 = [[NSExpressionDescription alloc] init];
[exprDesc3 setExpression:countExpr3];
[exprDesc3 setExpressionResultType:NSDateAttributeType];
[exprDesc3 setName:@"dateStart"];


NSFetchRequest *fr = [NSFetchRequest fetchRequestWithEntityName:@"TEvents"];
[fr setPropertiesToGroupBy:[NSArray arrayWithObjects:propDesc3, nil]];
[fr setPropertiesToFetch:[NSArray arrayWithObjects:propDesc3, exprDesc3, nil]];
[fr setResultType:NSDictionaryResultType];
NSError * error = nil;
NSArray *results = [context executeFetchRequest:fr error:&error];

dateShort is a nsdate category function which converts datatime to user's current zone:

-(NSString *) dateShort
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setCalendar:[NSCalendar currentCalendar]];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
[formatter setDoesRelativeDateFormatting:YES];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];

NSString *tmpValue = [formatter stringFromDate:self];
return tmpValue;
}

error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported function type passed to SQL store'

how to achieve this goal: convert datetime to current zone and group and count on (yy-mm-dd) on a core data entity?


Solution

  • I had to use NSExpression to achieve the goal. NSfetchResultController cannot group.