NSPredicate ステートメントで発生する可能性のあるエラーに関する多数のスタック オーバーフローの投稿を読みましたが、コードの何が問題なのかまだわかりません。
ユーザーが正規表現を使用して年を検索しているかどうかを確認しています。そうである場合は、年の最初の日から最後の日までの検索を作成します。
これが私のコードです:
//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))"'
私が間違っていることは何か分かりますか?