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

女生的网名这么多〃 提交于 2020-01-07 05:44:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/16942957/group-by-date-yyyy-mm-dd-with-nsfetchrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!