Retrieve existing values using a select query with a predicate. Use a unique value in the predicate. After you receive the object, update the object with the 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 update multiple Core Data objects without having to retrieve anything in 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) }
RajeshKumar R
source share