core data how to filter (NSPredicate) including a relationship requirement and given the relationship object? [closed]

↘锁芯ラ 提交于 2019-12-01 05:12:30

The predicate would be what you expect.

NSPredicate(format: "name = %@ && school = %@", "Tom", school)

However, you can get to the person without a predicate by using the relationship in the other direction and filter.

let tom = school.persons.filter { $0.name == "Tom" }.first

(You might have to cast your NSSet to Set<Person>).

Assuming the following model:

.. and you want to use NSPredicate .. you could try something like:

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 []
    }

}

However, don't forget other options (like traversing the relationship and using filter as suggested by @Mundi)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!