predicateWithFormat:
NSPredicateのメソッドを使用した(私にとって)奇妙なケースがあります。
以下を使用して、2つのNSPredicateインスタンスの説明をコンソールに記録します。
NSNumber *myNumber = [NSNumber numberWithInt:1];
NSString *predicateFormatByHand = [NSString stringWithFormat:@"self MATCHES 'chp%@_img[0-9]+\\.png'", myNumber];
NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:predicateFormatByHand];
NSLog(@"firstPredicate description: %@", firstPredicate);
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"self MATCHES 'chp%@_img[0-9]+\\.png'", myNumber];
NSLog(@"secondPredicate description: %@", secondPredicate);
これは以下を出力します:
firstPredicate description: SELF MATCHES "chp1_img[0-9]+.png"
secondPredicate description: SELF MATCHES "chp%@_img[0-9]+.png"
これらの説明は同じだと思います。
誰かがなぜそうではないのか説明できますか?
(この質問に続いて、埋め込まれた一重引用符のさまざまなエスケープシーケンスを試してみましたが、そうするときは、NSPredicateがフォーマット文字列を解析できないと文句を言い続けます。何が起こっているのかを知っていただければ幸いです。)
更新:1つの回答は、intではなくNSNumberの使用に問題があることを示唆しているため、次のようになります。
NSPredicate *thirdPredicate = [NSPredicate predicateWithFormat:@"self MATCHES 'chp%d_img[0-9]+\\.png'", [myNumber intValue]];
NSLog(@"thirdPredicate description: %@", thirdPredicate);
私はもともとこれから始めましたが、残念ながら出力は同じです:
thirdPredicate description: SELF MATCHES "chp%d_img[0-9]+.png"
(何かがフォーマット指定子が評価されていないことを意味します。)