Update core data object swift 3

后端 未结 2 1155
刺人心
刺人心 2021-02-05 21:52

I want to update a core data object in swift 3. After some googled I didn\'t found anything about swift 3. So my question is: how can I update a core data object in swift 3?

2条回答
  •  再見小時候
    2021-02-05 22:16

    Fetch the existing values using a fetch request with a predicate. Use a unique value in the predicate. Once you've fetched the object, update the object with new values and save the context.

    let empId = "001"
    let fetchRequest:NSFetchRequest = NSFetchRequest.init(entityName: "EmpDetails")
    let predicate = NSPredicate(format: "empId = '\(empId)'")
    fetchRequest.predicate = predicate
    do {
        let result = try persistentContainer.viewContext.fetch(fetchRequest)
        if let objectToUpdate = result.first as? NSManagedObject {
            objectToUpdate.setValue("newName", forKey: "name")
            objectToUpdate.setValue("newDepartment", forKey: "department")
            objectToUpdate.setValue("001", forKey: "empID")
            try persistentContainer.viewContext.save()
        }
    } catch {
        print(error)
    }
    

    Using NSManagedObject subclass

    let empId = "001"
    let fetchRequest: NSFetchRequest = Employee.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "%K = %@", #keyPath(Employee.id), empId)
    do {
      let results = try persistentContainer.viewContext.fetch(fetchRequest)
      if let employee = results.first {
        employee.name = "new name"
        employee.department = "new department"
      }
      try persistentContainer.viewContext.save()
    } catch let error as NSError {
      print(error.localizedDescription)
    }
    

    Batch updates

    Batch updates help to update multiple Core Data objects without having to fetch anything into memory.

    let batchUpdate = NSBatchUpdateRequest(entityName: "Employee")
    batchUpdate.propertiesToUpdate = [#keyPath(Employee.isActive): true]
    batchUpdate.affectedStores = persistentContainer.viewContext.persistentStoreCoordinator?.persistentStores
    batchUpdate.resultType = .updatedObjectsCountResultType
    do {
      let batchResult =  try coreDataStack.managedContext.execute(batchUpdate) as? NSBatchUpdateResult
      print(batchResult?.result)
    } catch let error as NSError {
      print(error.localizedDescription)
    }
    

提交回复
热议问题