我已经阅读了大量关于 NSPredicate 语句中可能出现的错误的 Stack Overflow 帖子,但我仍然无法弄清楚我的代码有什么问题。
我正在检查用户是否正在使用一些正则表达式搜索一年。如果是,我会创建一个搜索,从一年的第一天到最后一天。
这是我的代码:
//Check if searchBar.text is a year
NSString *expression = @"^\\d{4}$";
NSError *error = NULL;
//Regex test
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:searchBar.text options:0 range:NSMakeRange(0, [searchBar.text length])];
NSString *predicateString;
if(match){
//Search contains a year
NSDate *startDate = [_fullFormat dateFromString:[NSString stringWithFormat:@"%@-01-01",searchBar.text]];
NSDate *endDate = [_fullFormat dateFromString:[NSString stringWithFormat:@"%@-12-31",searchBar.text]];
predicateString = [NSString stringWithFormat:@"(departure CONTAINS[cd] '%1$@') OR (destination CONTAINS[cd] '%1$@') OR (aircraft.aircraftRegistration CONTAINS[cd] '%1$@') OR (aircraft.makeModel CONTAINS[cd] '%1$@') OR (duration CONTAINS[cd] '%1$@') OR (remarks CONTAINS[cd] '%1$@') OR ((flightDate >= %2$@) AND (flightDate <= %3$@))",searchBar.text,startDate,endDate];
}else{
//...
}
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:predicateString];
测井predicateString
产量:
(departure CONTAINS[cd] '2014') OR (destination CONTAINS[cd] '2014') OR (aircraft.aircraftRegistration CONTAINS[cd] '2014') OR (aircraft.makeModel CONTAINS[cd] '2014') OR (duration CONTAINS[cd] '2014') OR (remarks CONTAINS[cd] '2014') OR ((flightDate >= 2014-01-01 07:00:00 +0000) AND (flightDate <= 2014-12-31 07:00:00 +0000))
我因以下语句而崩溃:
'Unable to parse the format string "(departure CONTAINS[cd] '2014') OR (destination CONTAINS[cd] '2014') OR (aircraft.aircraftRegistration CONTAINS[cd] '2014') OR (aircraft.makeModel CONTAINS[cd] '2014') OR (duration CONTAINS[cd] '2014') OR (remarks CONTAINS[cd] '2014') OR ((flightDate >= 2014-01-01 07:00:00 +0000) AND (flightDate <= 2014-12-31 07:00:00 +0000))"'
知道我做错了什么吗?