iOS 的 NSPredicate 使用方法
· 阅读需 6 分钟
基本使用
格式化参数
查找name
是 Asriel 且 money
等于 50 的 Person
let fetchRequest = NSFetchRequest<Person>(entityName: "Person")
fetchRequest.predicate = NSPredicate(format: "name == %@ AND money == %i", "Asriel", 50)
完整的格式化说明符可以看官方文档,下面列举几个常用的:
%@
用于字符串、日期、数组等%i
用于整数%f
用于浮点数%K
用于 Keypath,实体属性
let integerPredicate = NSPredicate(format: "money == %i", 10000)
let doublePredicate = NSPredicate(format: "perimeter > %f", 3.14159)
let stringPredicate = NSPredicate(format: "name == %@", "Asriel")
// 下面两个是一样的效果
let datePredicate = NSPredicate(format: "due_date < %@", Date())
let keyPathDatePredicate = NSPredicate(format: "%K < %@", "due_date", Date())
比较
基本的比较符号有:==
,>
,<
,!=
等
let equalPredicate = NSPredicate(format: "name == %@", "Steve Jobs")
let notEqualPredicate = NSPredicate(format: "name != %@", "Steve Jobs")
let greaterPredicate = NSPredicate(format: "money > %i", 10000)
let greaterOrEqualPredicate = NSPredicate(format: "money >= %i", 10000)
let lesserPredicate = NSPredicate(format: "money < %i", 10000)
let lesserOrEqualPredicate = NSPredicate(format: "money <= %i", 10000)
复合比较:OR
,AND
// 匹配所有条件
let andPredicate = NSPredicate(format: "name == %@ AND money >= %i", "Steve Jobs", 10000)
// 匹配条件之一
let orPredicate = NSPredicate(format: "name == %@ OR money >= %i", "Steve Jobs", 10000)
不区分大小写比较:在比较符号后面加[c]
// 匹配 "jobs", "Jobs", "jObS"
let caseInsensitivePredicate = NSPredicate(format: "name ==[c] %@", "Jobs")