为什么我收到“无法解析NSPredicate”错误

时间:2013-05-08 23:57:12

标签: ios objective-c nspredicate

我构建了以下谓词,以便对Core Data存储使用MagicalRecord。

//  format the date correctly
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd*"];  //  HH:mm
NSString *formattedDate = [dateFormat stringFromDate:currentlySelectedDate];

NSString *stringPredicate = [NSMutableString stringWithFormat:
                             @"aPosX >= %f AND aPosX < %f AND %f > aPosY AND %f <= (aPosY + aPosH) AND aStartTime LIKE %@",
                             [staffIndex floatValue], [staffIndex floatValue] + 218, touchPoint.y, touchPoint.y, formattedDate];

NSPredicate *predicate =  ([NSPredicate predicateWithFormat: stringPredicate]);

它在最后一个语句崩溃,出现此错误:

  

* 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'无法解析格式字符串“aPosX&gt; = 218.000000 AND aPosX&lt; 436.000000 AND 15.000000&gt; aPosY AND 15.000000&lt; =(aPosY + aPosH)和aStartTime LIKE 2013-05-09 *“'

我已经尝试了我所知道的一切,搜索了Google和SO,但仍然不明白为什么它会失败...有人可以赐教我吗?

1 个答案:

答案 0 :(得分:3)

不要创建格式字符串,请使用谓词格式创建方法:

predicateWithFormat:

这允许谓词在其认为合适时处理格式参数(在需要时添加引号)。

对于日期,您需要修改谓词以使用范围。您不能直接检查日期的日期并忽略时间,因此您需要说:

date > startOfDay AND date < endOfDay

其中startOfDayendOfDay是NSDate实例(可能是使用NSDateComponents创建的)。