Good day to all, night.

I'm trying to learn CoreData and tritely can't figure out how to check and update the data.

This is my code, but how to update it :(

// Проверяем добавленн уже в список продукт или нет // Обновляем CoreData со ячейкой let row = self.test[indexPath.row].valueForKey("productName")! let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let fetchRequest = NSFetchRequest(entityName: "Products") if let fetchResults = try!managedObjectContext.executeFetchRequest(fetchRequest) as? [NSManagedObject] { for i in 0..<fetchResults.count { if String(fetchResults[i].valueForKey("productName")!) == row as! String { // Обновляем наши данные // Если у нас false 0 то устанавливаем true 1, и все наоборот if (fetchResults[i].valueForKey("addedToList")!.boolValue == true) { managedObjectContext.setValue(0, forKey: "addedToList") } else { managedObjectContext.setValue(1, forKey: "addedToList") } try!managedObjectContext.save() self.tableView.reloadData() } } } 

    2 answers 2

    Swift 3 save function

     func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } 
    • Please translate your answer in russian. - 0xdb

    Here’s how it works in swift 3.0

     func saveContext () { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext //Тут мы говорим, что если есть изменение - то сохранять данные еще раз if context.hasChanges { appDelegate.saveContext() } } 

    The second option is also available.

     func saveContext () { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext //Тут мы говорим, что если есть изменение - то сохранять данные еще раз if context.hasChanges { do { //Здесь мы просто сохраняемся try context.save() } catch { //Второй вариант это если нету сохранения - то выдает ошибку let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } }