Search code examples
swiftcore-dataswift5nsmanagedobjectcontext

Coredata update/insert for one to many relationship


I have a one to many relationship in my coredata object graph, typically User<->>Device. Lets say from my API i get a response of something as bellow

  [
   {
    user:"John"
    id:1
    devices:[
              {
                id:1
                name:"iPhoneX"
              },
              {
                id:2
                name:"Samsung Galaxy Plus"  
              } 
            ]
   },

   {
    user:"Peter"
    id:"2"
    devices:[
              {
                id:3
                name:"iPhone5s"
              },
              {
                id:4
                name:"Samsung Galaxy"  
              }
              
            ]
   }
  ]

Now the objective is to do a simple update/insert to my coredata tables. My Partial code as bellow for updating and inserting Device table

 func updateDevice (userID:String, apiDevicesArray:[APIResposeDevice]){
 
   for device in apiDevicesArray {

      let request:NSFetchRequest<Device> = Device.fetchRequest()
      request.predicate = NSPredicate(format:"id = %@", device.id)
 
      do{
           let searchResults = try self.privateMOC.fetch(request)
            if searchResults.count > 0  {

              //Update
             let update_device = searchResults.last

             update_device.name = device.name
             update_device.id = device.id

            }else{

             //Stuck with inserting a device to the proper user
              request.predicate = NSPredicate(format: "owner.id = %@, userID)
             
            do{
              let devicesArrayForUserID = try self.privateMOC.fetch(request)

             //How to insert a record to this array now ???

            }catch{
            }

            }

      }catch{
      }

   }

 }

Solution

  • First, you need to fetch the User.

    Then, you have to choices:

    1. user.devices.add(device)

    2. or if it's two ways relationship, then you can call device.user = user