NSPredicate - 无法为谓词生成 SQL,我想知道为什么?
我已经[盲目地]解决了我的问题,但没有了解根本原因。但我宁愿从专业人士那里理解一个概念。那么您能否告诉我为什么下面相同的代码一个有效,但另一个无效。
代码 1:不起作用
//Above code omitted...
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"gender == m"]; //NOTICE HERE
[request setPredicate:predicate];
NSError *error = nil;
self.people = [self.managedObjectContext executeFetchRequest:request error:&error];
//Below code omitted...
代码 2:起作用
//Above code omitted...
NSString *type = @"m";
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"gender == %@",type]; //NOTICE HERE
[request setPredicate:predicate];
NSError *error = nil;
self.people = [self.managedObjectContext executeFetchRequest:request error:&error];
//Below code omitted...
Forgot to tell about what error I got, I got SIGABRT on below line, When I executed Code 1.
self.people = [self.managedObjectContext executeFetchRequest:request error:&error];
还有一件事,在 GCC 错误中,它无法格式化谓词,因为“gender == m”。
Enlighten me!!
谢谢
I have already solved my problem [Blindly] without understanding root cause. But I would rather understand a concept from a professional. So could you please tell me why below identical code one works but another doesn't.
Code 1: Doesn't work
//Above code omitted...
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"gender == m"]; //NOTICE HERE
[request setPredicate:predicate];
NSError *error = nil;
self.people = [self.managedObjectContext executeFetchRequest:request error:&error];
//Below code omitted...
Code 2: Does work
//Above code omitted...
NSString *type = @"m";
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"gender == %@",type]; //NOTICE HERE
[request setPredicate:predicate];
NSError *error = nil;
self.people = [self.managedObjectContext executeFetchRequest:request error:&error];
//Below code omitted...
Forgot to tell about what error I got, I got SIGABRT on below line, When I executed Code 1.
self.people = [self.managedObjectContext executeFetchRequest:request error:&error];
And one more thing, in GCC error was it cannot format predicate because of "gender == m".
Enlighten me!!
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅 谓词编程指南(标题“文字”)。您可以在字符串中使用文字,但必须将它们括在引号中,这样
就可以了。当 predicateWithFormat 添加参数时,它知道它是一个字符串。当你只有 m 在那里时,它不知道如何处理它,因此会出现错误。
See the predicate programming guide (heading "Literals"). You can use literals in your string but you have to enclose them in quotes, so
Would have worked. When predicateWithFormat adds in the argument, it knows it is a string. When you just have m in there, it doesn't know what to do with it, hence the error.