2016-05-19 19 views
0

ここでは配列を文字列でフィルタリングするテストを示します。私の文字列が含まれていない場合には、文字( ')うまく動作( ')文字の問題で配列をフィルタリングするためのNSPredicate

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"b'en", @"Adam", @"Melissa", @"arbind", nil]; 

    //NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b'"]; -> it work 
    NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b''"]; -> it crash 
    NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate]; 
    NSLog(@"beginwithB = %@",beginWithB); 

私も'b\''または'b'''に私の文字列を変更しようとするが、それはまだここ

をクラッシュは、クラッシュログ

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "SELF contains[c] 'b'''"'

です

解決方法どんな助けでも大歓迎です。

+0

は多分無関係に役立ちますが、 'contains'は、その結果beginWith'命名されている述語に悪い候補者のように聞こえます... ' – Alladinian

+0

@Alladinianはい、それは私のテストだけです。私はこのコードをhttp://stackoverflow.com/a/25738783/5381331からコピーしています。あなたは訂正のためにありがとうございます –

答えて

2

の出力を取得し、この

NSString *searchword = @"b"; 
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchword]; 

を試してみてください、次のようにフィルタ結果に試してみてください:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"b'en", @"Adam", @"Melissa", @"arbind", nil]; 
     NSString *strToBeSearched = @"b'"; 

     //NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b'"]; -> it work 

     NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",strToBeSearched]; //-> it also work 

     //OR 

     NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b\\''"]; 


     NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate]; 
     NSLog(@"containB = %@",beginWithB); 
+0

この作品。ありがとうございます –

+0

@PhanVănLinhようこそ:-) – Microprocessor8085

2

あなたは

enter image description here

+0

excatの回答を使用する場合はdaskblinkknightの回答を、そうでない場合は私の回答をお試しください –

+0

あなたは正しい解決策を提供しますが、あなたが私に示す方法はあまり良くありません。 ( ')文字があなたのテストであなたの文字列に含まれていない文字列(')を尋ねるからです。とにかく私に正しい解決策を与えてくれてありがとう、) –

1

あなたはバックスラッシュを試みたときにはかなり接近していました。これは、NSPredicateが特殊文字をエスケープするために使用する文字です。しかし、2つのバックスラッシュが必要です。

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"b'en", @"Adam", @"Melissa", @"arbind", nil]; 
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b\\''"]; 
//                    ^^ 
NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate]; 
NSLog(@"beginwithB = %@",beginWithB); 

2つの理由が必要なのは、Objective-Cコンパイラです。これは、コード内のすべての文字列リテラルを処理し、遭遇したエスケープシーケンスを置き換えます。 NSPredicateにバックスラッシュを1つ表示する場合は、Objective-Cの文字列リテラルで円記号自体が\\とエンコードされているため、文字列リテラルには2つのバックスラッシュが必要です。

+0

'\\'仕事を追加してください。 –

0

あなたの名前は、その後b'enされている場合は、

NSString *name = @"b'en"; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == \"%@\"", name]; 

希望はこれが:)

+0

ありがとうございました。「このクラスはキー名に対応したキー値ではありません。」というエラーでクラッシュします。私は解決策を見つけました。あなたの助けに感謝 –

+0

あなたは大歓迎です:) – Lion

関連する問題