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

后端 未结 14 2716
有刺的猬
有刺的猬 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:55

    Swift 5

    You can create a method that can work to both, include and update. Considering you have an entity created on CoreData with the name Users:

     var context: NSManagedObjectContext 
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
     }
    
     let user: Users!
    
     let fetchUser: NSFetchRequest = Users.fetchRequest()
     fetchUser.predicate = NSPredicate(format: "id = %@", id as String)
    
     let results = try? context.fetch(fetchUser)
    
     if results?.count == 0 {
        // here you are inserting
        user = Users(context: context)
     } else {
        // here you are updating
        user = results?.first
     }
    
     user.id = id
     user.name = name
     ...
    
    
    try context.save()
    

提交回复
热议问题