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

后端 未结 14 2599
有刺的猬
有刺的猬 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
     var context:NSManagedObjectContext = appDel.managedObjectContext!
    
     var en = NSEntityDescription.entityForName("ENTITIES_NAME", inManagedObjectContext: context)
    
     let batchUpdateRequest = NSBatchUpdateRequest(entity: en!)
                batchUpdateRequest.resultType = NSBatchUpdateRequestResultType.UpdatedObjectIDsResultType
                batchUpdateRequest.propertiesToUpdate = ["OBJECT_KEY": "NEWVALUE"]
                var batchUpdateRequestError: NSError?
                context.executeRequest(batchUpdateRequest, error:&batchUpdateRequestError)
                if let error = batchUpdateRequestError {println("error")}
    

    good luck

    0 讨论(0)
  • 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> = 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()
    
    0 讨论(0)
提交回复
热议问题