我如何过滤(构建NSPredicate)以获取以下内容。
那么我的困惑/观察是:
偏好是SWIFT(但是如果有人在Objective-C中知道也可能对我有帮助)。所以我想再做的就是:
答案 0 :(得分:7)
谓词就是你所期望的。
NSPredicate(format: "name = %@ && school = %@", "Tom", school)
但是,您可以通过使用另一个方向的关系并过滤来找到没有谓词的人。
let tom = school.persons.filter { $0.name == "Tom" }.first
(您可能需要将NSSet
转换为Set<Person>
)。
答案 1 :(得分:4)
假设以下型号:
.. 和您想使用NSPredicate
..您可以尝试以下内容:
func searchSchool(school: School, firstName: String) -> [Person] {
let request = NSFetchRequest(entityName: "Person")
let predicate = NSPredicate(format: "school == %@ && firstName == %@", school, firstName)
request.predicate = predicate
// we will perform the request on the context associated with the School NSManagedObject
guard let context = school.managedObjectContext else {
print("provided School managed object is not associated with a managed object context")
return []
}
do {
return try context.executeFetchRequest(request) as? [Person] ?? []
} catch {
return []
}
}
但是,不要忘记其他选项(例如遍历关系并使用@Mundi建议的filter
)