Search code examples
ioscore-datansfetchrequest

group by date (yyyy/MM/dd) with NSFetchRequest


i have to count and group on more that 3 properties. i'm pulling my hair while grouping and counting on field with date (yyyy/mm/dd HH:mm:ss) i want to group by year - month - day and ignore the time. but i still need the time for detail view. time zone plays a big role here. so i just save it in utc format.

NSFetchRequest *fetchRequest    = [[NSFetchRequest alloc] init];
NSEntityDescription *entity     = [NSEntityDescription entityForName:@"logs"
                                              inManagedObjectContext:context;
NSAttributeDescription* att3 = [entity.attributesByName objectForKey:@"savedDate"];
NSExpression *keyPathExpression3 = [NSExpression expressionForKeyPath: @"savedDate"];
NSExpression *countExpression3 = [NSExpression expressionForFunction: @"count:"
                                                           arguments: [NSArray arrayWithObject:keyPathExpression3]];
NSExpressionDescription *att3Description = [[NSExpressionDescription alloc] init];
[expressionDescription3 setName: @"countSavedDate"];
[expressionDescription3 setExpression: countExpression3];
[expressionDescription3 setExpressionResultType: NSInteger32AttributeType];

...

[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:att1, att1Description, att2, att2Description, att3, att3Description, att4Description, att4, nil]];
[fetchRequest setPropertiesToGroupBy:[NSArray arrayWithObjects:att1, att2, att2, att3, nil]];
[fetchRequest setResultType:NSDictionaryResultType];

how can i can group by date (yyyy/MM/dd)? and be ok for converting to UTC?

thanks in advance

ps: group by on a transient property doesnt work and cant be fetched.


Solution

  • i had to convert date on the fly for local timezone with the fecth result controller as follow

    [self willAccessValueForKey:@"startDateTime"];
    
    NSDate * date = [self valueForKey:@"startDateTime"];
    
    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:date];
    [self didAccessValueForKey:@"callStartDateTime"];
    

    then manually group them and table view now use an array instead of fetch result controller.