1

I have a tableviewcontroller from where I am calling a another View Controller. This new controller populates the the object on selected table view cell. In the new view controller I am capturing a switch change.When the switch is turned on, I save the switch state into core data in the same object that was sent from the table view.

Below is the code that calls the new view controller, segue is "ShowDetails"

override func prepare(for segue: UIStoryboardSegue, sender:Any?){
    if (segue.identifier == SegueAddBooksViewController){
        if let destinationViewController = segue.destination as? bookDetailViewController {
            destinationViewController.managedObjectContext = persistentContainer.viewContext
        }
    }
        else{
            if (segue.identifier == "showDetails"){
                let selectedIndex = TableView.indexPathForSelectedRow
                let selectedBook = fetchedResultsController.object(at: selectedIndex!)
                if let controller:DetailsController = segue.destination as? DetailsController{

                     controller.books = selectedBook
                }

            }
    }
    }

below is the code when the switch state changes from Off to On.

func stateChanged(switchState: UISwitch){

    if switchState.isOn{
        let date = Date()
        books?.setValue(date, forKey: "endDate")
        books?.setValue(true, forKey: "bookState")

        do{
            try books?.managedObjectContext?.save()
        }catch let error as NSError{
            print("\(error)")
        }

        let dateFormat = DateFormatter()
        dateFormat.dateFormat = "MM/dd/YY"
        endBook.text = dateFormat.string(from: (books?.endDate)! as Date)

    }

Here books is a var of type BooksDetail which is a core data entity which is passed from the tableviewcontroller using the func prepare

my problem is that books?.managedobjectcontext.save() saves the modified data, however when I close the app and open it again(kill it completely) it will create a new entry in the table view with the updated data. If I don't kill the app, then everything works fine and my cell that I selected gets updated correctly. Is this the right way to update an existing object attributes?.

0 Answers0