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

uff*_* da 18 iphone core-data

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

我检查了模型以确保属性名称是正确的,我从这个SO问题中知道RHS的意思是"右手边",它引导我到"字符串"部分.我正在使用创建格式字符串

NSString *predicateString = [NSString stringWithFormat:@"attribute_name==%@", string];
Run Code Online (Sandbox Code Playgroud)

然后去取,我用这个:

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];
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Bre*_*ddy 42

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

NSString *predicateString = [NSString stringWithFormat:@"attribute_name==\"%@\"", string];
Run Code Online (Sandbox Code Playgroud)

  • 只有在使用NSPredicate predicateWithFormat方法时才会自动添加它们.您使用的是NSString stringWithFormat方法,这种方法并不是使用表达式谓词的正确方法 (2认同)

Dav*_*ong 19

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

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

NSString *predicateString = [NSString stringWithFormat:@"foo == \"%@\"", bar];
NSPredicate *p = [NSPredicate predicateWithFormat:predicateString];
Run Code Online (Sandbox Code Playgroud)

不要那样做.

改为:

NSPredicate *p = [NSPredicate predicateWithFormat:@"foo == %@", bar];
Run Code Online (Sandbox Code Playgroud)

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