1

如果直接添加到谓词,查询工作正常

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

如果创建查询然后传递给谓词,则查询不起作用

有解决办法吗?我宁愿不将谓词本身传递给方法

Author 是 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 回答