我正在构建一个复杂的NSPredicate,它根据许多变量而变化。似乎最有效的方法是将每个子句单独构建为字符串,将字符串组合成一个数组,将数组转换回字符串并使用predicateWithFormat将其读入谓词。它工作得很好,除了在我比较日期的一个案例中,我得到以下错误:
无法解析格式字符串“(已取消!= 1)&&(starttime> = 2016-12-18 13:50:41 +0000)”'
以下是构建此子句的行。
typePredClause = [NSString stringWithFormat:@"(starttime >=%@)",nowstr];
starttime
是实体中的NSDate
,这就是我得到nowstr
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *nowstr = [dateFormatter stringFromDate:[NSDate date]];
我知道只使用predicateWithFormat
并将字符串排除在外是理想的,但谓词非常复杂,因此构建它是唯一可行的。
有人可以建议如何解决这个问题吗?
作为参考,这里是我组合所有子句的代码。
if (typePredClause.length > 0)
[predArr addObject:typePredClause];
NSString *predStr = [predArr componentsJoinedByString:@"&&"];
predicate = [NSPredicate predicateWithFormat:predStr];
答案 0 :(得分:0)
如果starttime
是某个NSDate
属性,则不应该从日期创建字符串。只需使用NSDate
。
你创建谓词的方法都是错误的。不要使用一堆字符串来构建它。这样做:
NSPrediate *canceledClause = [NSPredicate predicateWithFormat:@"canceled != %d", someInt];
NSPredicate *startTimeClause = [NSPredicate predicateWithFormat:@"(starttime >= %@)", [NSDate date]];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[ canceledClause, startTimeClause ]];