How do you update a CoreData entry that has already been saved in Swift?

后端 未结 14 2723
有刺的猬
有刺的猬 2020-11-30 00:55

I\'m not sure what I\'m doing wrong here, but when I save the first time into coredata, it works just fine. When I try to overwrite that, it doesn\'t.

func t         


        
14条回答
  •  感动是毒
    2020-11-30 01:29

    //For Swift UI inside the view outside the body :)
    @Environment(.managedObjectContext) var managedObjectContext

    var isNewRecord = false
        let aNewContact: Contact!
          
        let fetchConcact: NSFetchRequest = Contact.fetchRequest() as! NSFetchRequest
        
        fetchConcact.predicate = NSPredicate(format: "record_id == %@", contactRemoteModel.contacts[i].record_id as CVarArg)
             
        let results = try? managedObjectContext.fetch(fetchConcact)
        
          if results?.count == 0 {
          // here you are inserting
          aNewContact = Contact(context: managedObjectContext)
          aNewContact.id = UUID()
          isNewRecord = true
                 print("Insert")
          } else {
             // here you are updating
              aNewContact = results?.first
              print("UpDate")
          }
    

提交回复
热议问题