使用NSFetchRequest按日期分组(yyyy / MM / dd)

时间:2013-06-05 14:45:47

标签: ios core-data nsfetchrequest

我必须计算并分组更多的3个属性。 我在分组和计算带日期的字段时拉我的头发(yyyy / mm / dd HH:mm:ss) 我想按年 - 月 - 分组,忽略时间。但我仍然需要时间进行详细查看。时区在这里起着重要作用。所以我只是以utc格式保存。

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];

我怎么能按日期分组(yyyy / MM / dd)?并且可以转换为UTC吗?

提前致谢

ps:group by on transient属性不起作用且无法获取。

1 个答案:

答案 0 :(得分:0)

我必须使用fecth结果控制器动态转换当地时区的日期,如下所示

[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"];

然后手动对它们进行分组,表视图现在使用数组而不是获取结果控制器。