1

述語に直接追加すると、クエリは正常に機能します

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author == %@", author];
[request setPredicate:predicate];
[self.managedObjectContext executeFetchRequest:request error:nil];

作成してから述語に渡した場合、クエリは機能しません

解決策はありますか?述語自体をメソッドに渡さない

著者はNSManagedObjectのサブクラスです

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "%@"'

[self fetchObjectsWithQuery:[NSString stringWithFormat:@"author == %@", author];

- (void)fetchObjectsWithQuery:(NSString *)query
{
   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@", query];
   [request setPredicate:predicate];
   [self.managedObjectContext executeFetchRequest:request error:nil];
}
4

2 に答える 2

2

フォーマット文字列は、で異なる動作をします

NSString *query = [NSString stringWithFormat:@"author == %@", author] // (1)

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author == %@", author]

特に、プレースホルダー「%@」と「%K」の意味は異なります。

(1)次の形式の文字列を生成します

"author == <textual description of author object>"

で使用できない

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@", query];

したがって、述語を文字列として事前にフォーマットすることはできません。問題を示す別の例:

[NSPredicate predicateWithFormat:@"author == nil"]

動作しますが

[NSPredicate predicateWithFormat:"%@", @"author == nil"]

ではない。

于 2012-10-01T11:33:24.230 に答える
0

NSPredicateオブジェクトを作成して渡さない理由はありません。やりたいことを正確に行う方法はいくつかありますが、述語を使用するよりも表現力が弱いか、基礎となるロジックを複製する必要がありますNSPredicate

于 2012-09-30T21:37:56.620 に答える