嵌套提取请求

时间:2016-02-18 12:59:51

标签: swift core-data relationship nspredicate

在我的项目中,我有两个实体:personEntity& municipalEntity。它们之间具有多对多的反向关系。我在NSFetchRequest上执行personEntity以获取某人的详细信息:

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDelegate.managedObjectContext
    let personRequest = NSFetchRequest(entityName: "personEntity")
    let personPred = NSPredicate(format: "surname = %@", "Smith")
    personRequest.predicate = personPred
    do {
        let personsList = try context.executeFetchRequest(personRequest)
        // this all clear enough up to this point

此时,我尝试在第一个内嵌第二个谓词FetchRequest。对于来自municipalEntity的对象,此请求应在其peopleInMunicipality关系属性中搜索personsList

        for selectedPeople in personsList {
            let municipalRequest = NSFetchRequest(entityName: "municipalEntity")
            let municipalPred = NSPredicate(format: "peopleInMunicipality = %@", selectedPeople)
            municipalRequest.predicate = municipalPred
            do {
                let municipalitiesWithResidentsCalledSmithList = try context.executeFetchRequest(municipalRequest)

然后爆炸......编译器抱怨并建议我需要在定义第二个谓词的行中更改两件事。它建议改为......

            let municipalPred = NSPredicate(format: "peopleInMunicipality = %@", argumentArray: selectedPerson as? [AnyOject])

编译器现在很高兴但是当我运行代码时,它会在建议的argumentArray:代码部分出现EXC_BAD_ACCESS错误而崩溃。 知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

vadian是对的。您不需要第二次获取请求。如果peopleInMunicipality的反向关系被称为municipalities,则selectedPeople的城市为selectedPeople.municipalities

如果您确实要执行第二次获取请求,则谓词格式为peopleInMunicipality CONTAINS %@

答案 1 :(得分:0)

因为我无法发表评论。您可以像这样在MunicipalEntity上尝试SubQuery:

{{1}}

在市政实体上使用此谓词