11

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?

1
  • In what ways do you think updating a managed object is different in Swift 3? Do you run into specific problems which didn't occur in Swift 2? If so, please share more details. Commented Sep 13, 2016 at 10:26

2 Answers 2

23

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<NSFetchRequestResult> = 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> = 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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm!
0

Pass unique id in variable "id"(Unique variable created in Core data model) and all the variable as you want to update values:

func context() ->  NSManagedObjectContext {
    let context=(UIApplication.shared.delegate as!AppDelegate).persistentContainer.viewContext
        return context
}



func save() {
    (UIApplication.shared.delegate as! AppDelegate).saveContext()
}

func UpdateCartByTestId(id:Int64,name:String) {
    let fetchRequest =
            NSFetchRequest<NSManagedObject>(entityName: "Update")
    fetchRequest.returnsObjectsAsFaults = false
    fetchRequest.predicate = NSPredicate(format:"id == %d",id)

    let result = try? context().fetch(fetchRequest)

    if result?.count == 1 {

        let dic = result![0]
        dic.setValue(id, forKey: "id")
        dic.setValue(name, forKey: "name")
        save()
    }
}

2 Comments

Can you please add more detail about your solution to your answer, please?
Pass unique id in variable "id"(Unique variable created in Core data model) and all the variable as you want to update values.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.