无法为谓词生成SQL(_STRING PREDICATE_)(RHS上的问题)是什么意思?

时间:2011-07-15 23:16:52

标签: iphone core-data

我正在尝试使用Core Data为iPhone开发应用程序,而我正在使用非常基本的谓词来抓取对象。 (即attribute_name == string)

我检查过模型以确保属性名称是正确的,我从this SO question知道RHS的意思是“右手边”,它引导我进入“字符串”部分。我正在使用

创建格式字符串
NSString *predicateString = [NSString stringWithFormat:@"attribute_name==%@", string];

然后去取,我正在使用它:

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:_entityName inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];

我错过了什么?什么可能导致此错误发生?

感谢。

2 个答案:

答案 0 :(得分:42)

如果你真的想要使用NSString stringWithFormat:消息,你需要引用字符串,或者你可以使用格式和参数的NSPredicate predicateWithFormat:消息,因为它将使用rhs“做正确的事”在你的情况下(我建议你使用没有引号的NSPredicate方法)

NSString *predicateString = [NSString stringWithFormat:@"attribute_name==\"%@\"", string];

答案 1 :(得分:19)

你做错了。您不应该创建格式字符串。

我猜(基于你对@Brent的答案的反应),你正在做这样的事情:

NSString *predicateString = [NSString stringWithFormat:@"foo == \"%@\"", bar];
NSPredicate *p = [NSPredicate predicateWithFormat:predicateString];

不要那样做

请改为:

NSPredicate *p = [NSPredicate predicateWithFormat:@"foo == %@", bar];

如果bar恰好包含"字符,则第一个将失败。第二个不会。