Updating the main swift 3 data object

I want to update the main data object in swift 3. After some googled I did not find anything about swift 3. So my question is: how can I update the main data object in swift 3?

+10
ios swift3
source share
2 answers

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) } 
+21
source share

Pass the unique identifier to the variable "id" (a unique variable created in the Core data model) and all the variables as you want to update the 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() } } 
0
source share

All Articles