I had to use NSExpression
to achieve the goal. NSfetchResultController
cannot group.
nsexpression with custom function core data
-
29-06-2022 - |
문제
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?
해결책 2
다른 팁
I think you are on the wrong path here. There is a much simpler solution to your problem.
You should use a NSFetchedResultsController and use a transient property on your entity to serve as the section header. You calculate the date in a category of your managed object subclass. Then it is as simple as specifying your transient property name in the sectionNameKeyPath
when creating the fetched results controller.
Apple has a good working example that for most purposes you can use out of the box.