1

假设我们有 2 个实体:

- 人(姓名,年龄,..)

-房子(颜色)

house.addToPeople (newPeople)我们为每个房子记录了几次数据

我们想让房子里的所有人都染成蓝色

我们如何获取这个?

我试过这段代码,但它得到了所有人

        let appD = UIApplication.shared.delegate as! AppDelegate
            let context = appD.persistentContainer.viewContext
        
        
        let peopleFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "People")

        let houseFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "House")               
        houseFetch.fetchLimit = 1       
        houseFetch.predicate = NSPredicate(format: "color = %@", "blue")
    
        ...
        
        let res = try? context.fetch(peopleFetch)
        let resultData = res as! [People]

这个怎么做 ?

4

2 回答 2

0

试试这个功能。它所做的是获取所有人员并创建一个包含所有结果的数组。

func getAllItems() -> [People]? {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "People")
        request.returnsObjectsAsFaults = false
        
        do {
            let result: NSArray = try context.fetch(request) as NSArray
            return (result as? [People])!
        } catch let error {
            print("Errore recupero informazioni dal context \n \(error)")
        }
        return nil
    }

如果您想按照某些条件(例如颜色)执行搜索,请在 之后使用以下代码request

//Here i'm searching by index, if you need guidance for your case don't hesitate asking
 request.predicate = NSPredicate(format: "index = %d", currentItem.index) 

编辑:实际上上面的代码只是为了得到所有人,如果你想根据房屋进行搜索,请执行以下操作:

  func retrieve()-> [People]{
//Fetch all of the houses with a certain name
        let houseRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "House")
        houseRequest.predicate = NSPredicate(format: "name = %@", "newName") //This seearch is by name
        houseRequest.returnsObjectsAsFaults = false
        do {
//put the fetched items in an array
            let result: NSArray = try context.fetch(houseRequest) as NSArray
            let houses = result as? [Houses]
//Get the people from the previous array
            let people: [People]? = (houses.people!.allObjects as! [People])
            return people
        } catch let error {
            print("Errore recupero informazioni dal context \n \((error))")
        }
            return nil
        
    }
于 2020-12-20T22:17:41.327 回答
0

谢谢您的回答 !

在这个例子中,“houses”是一个数组,所以我们必须添加一个索引➔houses[0].people!.AllObjects

非常感谢您的解释。

于 2020-12-21T21:03:58.273 回答