[英]Unable to fetch from coreData using Predicate as String?
I am unable to fetch data using a string as a direct argument to NSPredicate. 我无法使用字符串作为NSPredicate的直接参数来获取数据。 Is there any difference between these two,
两者之间有什么区别吗?
//Working case
fetchRequest.predicate = NSPredicate(format: "role == %@","GK")
In the above case, I am able to fetch the data with the predicate. 在上述情况下,我可以使用谓词获取数据。
//Not Working
predicateString = String(format:"role == %@","GK")
fetchRequest.predicate = NSPredicate(format: predicateString)
Here I am unable to fetch the data. 在这里,我无法获取数据。
The only difference between the above two cases is that I'm using a String variable to define the predicate. 以上两种情况之间的唯一区别是,我使用的是String变量来定义谓词。 What is wrong here?
怎么了
When the %@ is replaced with a string variable when instantiating a NSPredicate the string variable is automatically surrounded by quotes so in your example the predicate becomes role == 'GK'
在实例化NSPredicate时将%@替换为字符串变量时,该字符串变量会自动被引号引起来,因此在您的示例中,谓词将成为
role == 'GK'
If you want to use String(format:...) you need to add the quotes yourself but in my opinion it's better to use NSPredicate(format:...) directly instead to avoid issues like this. 如果要使用String(format:...),则需要自己添加引号,但我认为最好直接使用NSPredicate(format:...),以避免出现此类问题。
Format of NSPredicate
is as following, where it expects a format, and format contains equaliser. NSPredicate
格式如下,它需要一个格式,并且格式包含均衡器。
NSPredicate(format: <String>, <args: CVarArg...>)
let predicate1 = NSPredicate(format: "role == %@", "GK")
Here, if you will check the predicate1.predicateFormat
, then you will get: 在这里,如果您要检查
predicate1.predicateFormat
,那么您将获得:
"role == \\"GK\\"" , “角色== \\” GK \\“” ,
which equilise role with string "GK"
and return result in array
. 使角色与字符串
"GK"
相等,并在array
返回结果。
But for, 但对于,
let predicateString = String(format:"role == %@","GK")
let predicate2 = NSPredicate(format: predicateString)
You replaced the equaliser with simple string, which fails to return anything. 您用简单的字符串替换了均衡器,该字符串无法返回任何内容。 You can check with
predicate1.predicateFormat
which will return: 您可以使用
predicate1.predicateFormat
进行检查,该查询将返回:
"role == GK" “角色== GK”
Here you can use "role == 'GK'"
if you want to use string. 如果要使用字符串,可以在此处使用
"role == 'GK'"
。
Hope it will help. 希望它会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.