Created
December 29, 2011 18:34
-
-
Save acwright/1535473 to your computer and use it in GitHub Desktop.
Create dynamic date predicate using now() function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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