一对多关系的 Coredata update/insert

Coredata update/insert for one to many relationship

我的核心数据对象图中有一对多关系,通常是用户<->>设备。比方说,从我的 API 我得到的回复如下

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

现在 objective 是对我的核心数据 table 做一个简单的 update/insert。我的部分代码如下,用于更新和插入设备 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{
      }

   }

 }

首先,您需要获取用户。

那么,你必须选择:

  1. user.devices.add(device)

  2. 或者如果是双向关系,那么你可以调用device.user = user