0

I am trying to retrieve some results based on the "begin" (NSDate) field. However, it always returns 0 results. And I can't figure out what I am doing wrong. I am guessing it has something to do with the NSDate type but I have double checked and everything seems correct.

I have checked this answer, and this one also. But to no avail…

Any help would be greatly appreciated.

Here is the definition in the model file :

@property (nonatomic, retain) NSDate * begin;

And here is the code from which I call the fetch Request.

-(void)getCalendarListForDatesFrom:(NSDate  *)startDate 
                                To:(NSDate  *)endDate 
                           inViews:(NSArray *)daysArray
{

    // Reset dates to Midnight
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    NSUInteger preservedComponents = (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit);

    startDate = [calendar dateFromComponents:[calendar components:preservedComponents    
                                                         fromDate:startDate   ]
                ];
    endDate =   [calendar dateFromComponents:[calendar components:preservedComponents 
                                                         fromDate:endDate     ]
                ];


    NSLog(@"Get Events for dates %@ to %@", startDate, endDate);

    _isRetrievingData = YES;

    NSManagedObjectContext *MOC;
    NSPredicate *predicate;
    NSError *error              = nil;
    NSString *entityName        = @"CalendarEvent";

    //AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //BOOL doIHaveConnexion = [appDelegate getConnexion];

    MOC = self.managedObjectContext;
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName 
                                              inManagedObjectContext:MOC        ];

    // Fetch Request
    NSFetchRequest *fetchRequest;
    fetchRequest = [[NSFetchRequest alloc] init];
    if (!fetchRequest) 
    {
        fetchRequest = [[NSFetchRequest alloc] init];
    }

    [fetchRequest setEntity:entity];

    // Filter
    NSLog(@"Filter results between dates %@ and %@", startDate, endDate);
    predicate = [NSPredicate predicateWithFormat:@"(%K >= %@) AND (%K <= %@)", @"begin", startDate, @"begin", endDate];
    //predicate = [NSPredicate predicateWithFormat:@"(%K > %@)", @"begin", [NSDate date]];

    NSLog(@"PREDICATE = %@", predicate);
    NSLog(@"Set Predicate");

    [fetchRequest setPredicate:predicate];

    NSLog(@"Set Sort Descriptor");
    NSSortDescriptor *beginDateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"begin" 
                                                                        ascending:YES 
                                                                         selector:@selector(localizedCaseInsensitiveCompare:)
                                            ];
     NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:beginDateDescriptor, nil];

     NSLog(@"Fetch");
     [fetchRequest setSortDescriptors:sortDescriptors];


     NSLog(@"Init Fetch");
     // Initialize Fetched Results Controller
     if (!self.fetchedResultsController) 
     {
         self.fetchedResultsController = [[NSFetchedResultsController alloc]  
                                                 initWithFetchRequest:fetchRequest 
                                                 managedObjectContext:MOC 
                                                   sectionNameKeyPath:nil 
                                                            cacheName:nil          ];
     }

     NSLog(@"Perform Fetch");
     // Perform Fetch
     [self.fetchedResultsController performFetch:&error];

     NSArray *calEvents = [MOC executeFetchRequest:fetchRequest error:&error];

     currentCalEvents = [calEvents mutableCopy];

     if (error) 
     {
         NSLog(@"Unable to execute fetch request.");
         NSLog(@"%@, %@", error, error.localizedDescription);
     } 
     else 
     {
        NSLog(@"TOTAL CALENDAR EVENTS %lu",(unsigned long)[calEvents count]);
        NSLog(@"currentCalEvents = %@", currentCalEvents);

        [self addCalendarEventsToDays: daysArray];
     }

     fetchRequest = nil;
}

Here are the logs from the console :

Filter results between dates 2015-01-02 23:00:00 +0000 and 2015-01-07 23:00:00 +0000
PREDICATE = begin >= CAST(441932400.000000, "NSDate") AND begin <= CAST(442364400.000000, "NSDate")
Set Predicate
Set Sort Descriptor
Fetch
Init Fetch
Perform Fetch
TOTAL CALENDAR EVENTS 0
Community
  • 1
  • 1
Benjamin
  • 8,128
  • 3
  • 34
  • 45
  • 1
    The code that logs "Perform fetch" and "TOTAL CALENDAR EVENTS 0" seems to be missing in your question. Also, are you sure that you have records having the date in the given interval in your persistent store? – Michał Ciuba Jan 05 '15 at 14:01
  • http://stackoverflow.com/a/1965564/1387438 – Marek R Jan 05 '15 at 14:23
  • OK. I have updated my code to show the complete method. @Michael Ciuba : Yes, I have checked my SQLLite DB and I should retrieve 4 results… – Benjamin Jan 05 '15 at 16:25
  • @MarekR : Thanks for the link but I still seem to have the same problem… – Benjamin Jan 05 '15 at 16:26
  • 1
    Does your fetch work when you don't set a date predicate? If so, try using manual dates, `[NSDate date]` for today and `[NSDate distantPast]` to make sure you get all results. – shim Jan 05 '15 at 16:35
  • @shim:yes. If I remove the the predicate I get all results. However, if I use [NSDate date] and [NSDate distantPast] I get 0 results. I had already tried this hence my inclination to think that it comes from the format in which I store my dates… – Benjamin Jan 05 '15 at 20:52
  • EDIT : I noticed I had some dupes in my DB. So I deleted them and recreated the DB without dupes. And suddenly my code worked… To further go my tests I tried adding a duplicate entry and… sure as anything suddenly the code doesn't work anymore (return 0 results). Anyone see why ? Is this a bug ? – Benjamin Jan 06 '15 at 15:55

0 Answers0