Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update core data object swift 3

Tags:

ios

swift3

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?

like image 741
Roberto Tonini Avatar asked Aug 03 '16 18:08

Roberto Tonini


1 Answers

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)
}
like image 141
RajeshKumar R Avatar answered Oct 29 '22 06:10

RajeshKumar R