Skip to content

Instantly share code, notes, and snippets.

@acwright
Created December 29, 2011 18:34
Show Gist options
  • Save acwright/1535473 to your computer and use it in GitHub Desktop.
Save acwright/1535473 to your computer and use it in GitHub Desktop.
Create dynamic date predicate using now() function
// The goal...
[NSPredicate predicateWithFormat:@"dateModified >= CAST(CAST(now(), \"NSNumber\") - %d, \"NSDate\")", (30*86400)];
//"now()" is a function and takes no arguments
NSExpression *now = [NSExpression expressionForFunction:@"now" arguments:[NSArray array]];
//CAST(now(), 'NSNumber')
NSArray *castNowArguments = [NSArray arrayWithObjects:now, [NSExpression expressionForConstantValue:@"NSNumber"], nil];
NSExpression *castNow = [NSExpression expressionForFunction:@"castObject:toType:" arguments:castNowArguments];
//CAST(now(), 'NSNumber') [+/-] {a time interval}
NSArray *relativeTimestampArguments = [NSArray arrayWithObjects:castNow, [NSExpression expressionForConstantValue:[NSNumber numberWithDouble:(30*86400)]], nil];
NSExpression *relativeTimestamp = [NSExpression expressionForFunction:@"from:subtract:" arguments:relativeTimestampArguments];
//CAST(CAST(now(), 'NSNumber') [+/-] {a time interval}, 'NSDate')
NSArray *castToDateArguments = [NSArray arrayWithObjects:relativeTimestamp, [NSExpression expressionForConstantValue:@"NSDate"], nil];
NSExpression *castToDate = [NSExpression expressionForFunction:@"castObject:toType:" arguments:castToDateArguments];
NSPredicate *predicate = [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"dateModified"]
rightExpression:castToDate
modifier:NSDirectPredicateModifier
type:NSGreaterThanOrEqualToComparison
options:0];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment