Search code examples
iosswiftcore-dataone-to-manyfetchrequest

Swift - Get one-to-many relationship


let's imagine that we have 2 entities:

-People (name, age, ..)

-House (color)

we recorded the data several times with house.addToPeople (newPeople) for each house

we want to get all the people of the house colored blue

how do we fetch this?

I tried this code but it gets all the people

        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]

how to do this ?


Solution

  • Try this function. What it does is fetching all of the People and creating an array with all of the results.

    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
        }
    

    If you want to perform your search following certain criteria such as a color, use the following code after 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) 
    

    Edit: actually the code above is just to get all of the people, if you want to base your search on the houses do the following:

      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
            
        }