Search code examples
objective-ccore-data

search by date in coredata


How to predict all the data that inserted the last week , the last month yesterday

I have nsdate field in my coredata but I don't know how to search using it


Solution

  • I suppose you have a fetchedResultsController set up for retrieving objects from the database. You have to add an NSPredicate to your fetchRequest when you set up the fetchedResultsController.

    Dates shamelessly stolen from here

    //You can set up your custom dates like this
    NSDate *today = [NSDate date];
    
    NSDate *yesterday = [today addTimeInterval: -86400.0];
    NSDate *thisWeek  = [today addTimeInterval: -604800.0];
    NSDate *lastWeek  = [today addTimeInterval: -1209600.0];
    
    // This predicate retrieves all the object created since last week.
    NSpredicate *predicate = [NSPredicate predicateWithFormat:@"yourDateField >= %@ ", lastWeek];
    [fetchRequest setPredicate:predicate];    
    
    // You can add sorting like this
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"yourDateField" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    
    [fetchRequest setSortDescriptors:sortDescriptors];