Search code examples
ioscore-datacountnsdatensmanagedobject

How to count unique dates of CoreData objects?


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

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

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

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

Thanks!


Solution

  • 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

    And then just calculate these groups.

    EDIT:

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

    some file

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

    That's all!