ios - 无法使用谓词作为字符串从 coreData 中获取?

标签 ios swift core-data

我无法使用字符串作为 NSPredicate 的直接参数来获取数据。这两者有什么区别吗,

//Working case
fetchRequest.predicate = NSPredicate(format: "role == %@","GK")

在上述情况下,我可以使用谓词获取数据。

//Not Working
predicateString = String(format:"role == %@","GK")
fetchRequest.predicate = NSPredicate(format: predicateString)

这里我无法获取数据。

上述两种情况的唯一区别是我使用字符串变量来定义谓词。这里有什么问题?

最佳答案

当实例化 NSPredicate 时将 %@ 替换为字符串变量时,字符串变量会自动用引号引起来,因此在您的示例中谓词变为 role == 'GK'

如果你想使用 String(format:...) 你需要自己添加引号,但我认为最好直接使用 NSPredicate(format:...) 来避免这样的问题。

关于ios - 无法使用谓词作为字符串从 coreData 中获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50720681/

相关文章:

ios - Core Data/NSFetchedResultsController - 注册与获取的对象相关的更改对象

ios - 辅助功能顺序

swift - Swift 中的可空整数

iphone - 适用于iPhone应用程序的iOS 3.0+兼容性

swift - UIView绘制中的SQLite3查询(_ :) not working with CATiledLayer

swift - 在 Swift 中实现 "Either"结构

iphone - 每次触摸UIButton时将值增加1

ios - 如何在 Swift 的核心数据中保存多个项目

cocoa - 核心数据中存在看似有效对象的 "Dangling reference to an invalid object"错误

ios - UITableViewCell 的 UIButton subview 取消选择 UITableViewCell?