Search code examples
ioscore-datansdatenspredicatenstimeinterval

Can I use date calculation inside NSPredicate


I have a NSDate attribute in a Drug entity in CoreData, called expiringDate, and I need to fetch all the entities with a date within an interval of 30 days before expiringDate. I can't figure out if and how I can include this kind of calculation inside NSPredicate. I'd like to avoid to use a new attribute, kind of thirtyDayFromExpiryDate, inside the DB structure, obtain the date by NSTimeInterval calculation and use that in the predicate to get rid of the issue. Is it possible?


Solution

  • You're trying to return all results with:

    expiryDate > [NSDate date] && aMonthToExpityDate <= [NSDate date]
    

    where

    aMonthToExpiryDate = expiryDate - 30 days
    

    So you can simplify rewrite your query as:

    expiryDate > [NSDate date] && (expiryDate - 30 days) <= [NSDate date]
    

    or

    expirayDate > [NSDate date] && (expiryDate <= [NSDate date] + 30 days)
    

    Which you can now use in a predicate since the calculation is static:

    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"expiryDate BETWEEN (%@, %@)",
                              [NSDate date],
                              [NSDate dateWithTimeIntervalSinceNow:k30Days]];