Coredata更新/插入一对多关系

时间:2020-07-22 02:43:42

标签: swift core-data swift5 nsmanagedobjectcontext

我的coredata对象图中有一对多关系,通常是User <->> Device。可以说,从我的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"  
              }
              
            ]
   }
  ]

现在的目标是对我的coredata表进行简单的更新/插入。我的部分代码如下所示,用于更新和插入设备表

 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 个答案:

答案 0 :(得分:0)

首先,您需要获取用户。

然后,您必须选择:

  1. user.devices.add(device)

  2. 或如果是两种关系,则可以调用device.user = user