0
votes

I am building a complicated NSPredicate that varies depending on many variables. The method that seems to work best is to build each clause separately as a string, combine the strings into an array, covert the array back into a string and read it into the predicate using predicateWithFormat. It works great except in the one case where I am comparing dates and I get the following error:

Unable to parse the format string "(canceled != 1)&&(starttime >=2016-12-18 13:50:41 +0000)"'

Here is the line where I build this clause.

typePredClause = [NSString stringWithFormat:@"(starttime >=%@)",nowstr];

starttime is an NSDate in the entity and this is how I get nowstr

   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
             NSString *nowstr = [dateFormatter stringFromDate:[NSDate date]];

I know that it would be ideal to just use predicateWithFormat and leave the strings out of it but the predicate is so complicated that building it is the only to go.

Can anyone suggest how to fix this?

As reference, here is code where I combine all the clauses.

if (typePredClause.length > 0)
[predArr addObject:typePredClause];
NSString *predStr = [predArr componentsJoinedByString:@"&&"];
predicate = [NSPredicate predicateWithFormat:predStr];
1

1 Answers

0
votes

If starttime is some NSDate property, you should not create a string from the date. Just use the NSDate.

And your approach to creating your predicate is all wrong. Do not build it using a bunch of strings. Do it like this:

NSPrediate *canceledClause = [NSPredicate predicateWithFormat:@"canceled != %d", someInt];
NSPredicate *startTimeClause = [NSPredicate predicateWithFormat:@"(starttime >= %@)", [NSDate date]];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[ canceledClause, startTimeClause ]];