如何计算CoreData对象的唯一日期? [英] How to count unique dates of CoreData objects?

查看:136
本文介绍了如何计算CoreData对象的唯一日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个正确的方法来计算CoreData对象中具有NSDate类型属性的唯一天数。

I need a proper way to count how many unique days there are in CoreData objects with a property of type NSDate.

例如,我有以下: / p>

For example, I have the following:

<Object>.date = "2014-05-15 21:29:12 +0000";
<Object>.date = "2014-05-15 21:49:34 +0000";
<Object>.date = "2014-05-16 13:29:23 +0000";
<Object>.date = "2014-05-16 20:49:50 +0000";
<Object>.date = "2014-05-16 22:01:53 +0000";
<Object>.date = "2014-05-20 03:32:12 +0000";
<Object>.date = "2014-05-20 12:45:23 +0000";
<Object>.date = "2014-05-20 14:15:50 +0000";
<Object>.date = "2014-05-20 20:20:05 +0000";

在这种情况下,结果必须为3,因为有3个不同的日子,2014-05-15 ,2014-05-16和2014-05-20

In this case, the result must be 3 because there are 3 different days, 2014-05-15, 2014-05-16 and 2014-05-20

以任何方式处理这个问题?
我尝试了NSPredicate但是没有成功

Any way to deal with this problem? I tried with NSPredicate but I did not succeed

谢谢!

推荐答案

这很容易。让我告诉你我要做什么。

That's easy. Let me show you what I'm going to do for it.

使用排序说明键对结果进行分组。此示例可帮助您了解如何实现。

Group your results with sort description key. This example helps you to understand how it can be realized.

https://developer.apple.com/library/ios/samplecode/DateSectionTitles/Introduction/Intro.html

然后计算这些组。

编辑:

NSDate + Utils。 h

- (NSDate *) dateWithoutTime

NSDate + Utils.m

-(NSDate *) dateWithoutTime
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:self];
    return [calendar dateFromComponents:components];
}

某些文件 b

- (NSUInteger) someObjectsCount
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"SomeObject"];

    NSString *key = @"date.dateWithoutTime";

    fetchRequest.sortDescriptors = @[[[NSSortDescriptor alloc] initWithKey:key
                                                                 ascending:YES]];

    NSManagedObjectContext *context;
    context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

    NSFetchedResultsController *aFetchedResultsController;
    aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                    managedObjectContext:context
                                                                      sectionNameKeyPath:key
                                                                               cacheName:nil];
    [aFetchedResultsController performFetch:nil];

    return [[aFetchedResultsController sections] count];
}

就是这样!

这篇关于如何计算CoreData对象的唯一日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆