2

My question is a bit confused. I've a ViewController that shows to the user some attributes, these attributes are in a dictionary. For edit these attributes I've another ViewController, that when I "segue" to that I pass the attributes in the default way, like this:

viewController.value = self.value

On the second ViewController (view controller of edition) I've options to Back to ViewController and Save the changes, so, I can change values without save or save. When I change values and not save, just back to view controller, the value is changed in the previous view controller. I don't understannd how this happens. I will try show with images.

My first view controller is: ViewContollerSale.swift

My second (edit) view controller is: ViewControllerCreateSale.swift

ViewControllerSale.swift

var saleOrder : SaleOrder?  // at this point it's populated


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("===> VcSale: prepare")
    if segue.identifier == "segueEditOrder" {
        print("segue: segueEditOrder")
        let editVc = segue.destination as! ViewControllerCreateSale
        editVc.saleToEdit = true
        if saleOrder != nil {
            editVc.sale = saleOrder!
        }
    }
}

ViewControllerCreateSale.swift

The function that set value is showed below. But I think that this changes only value of instance context of ViewControllerCreateSale.swift, but when I back view controller the value is changed also on the previous view controller!

var sale: SaleOrder = SaleOrder()

case Notification.Name.opEntrega:
    aux = notf.object as! String
    sale.attributes["delivery_term_id"] = aux == "CIF" ? Int32(1) : Int32(2)
    let cell = tableOptionsSelect.cellForRow(at: IndexPath(row: 3, section: 0)) as! CellSelectionCreateSale
    cell.lblOptionSelect.text = aux
    break

enter image description here

enter image description here

enter image description here

enter image description here

Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75
Augusto
  • 3,825
  • 9
  • 45
  • 93

1 Answers1

1

When you assign a SaleOrder to the second view controller you are passing a reference to the SaleOrder instead of a copy.

That means whenever you update the SaleOrder on the second screen you are updating the same SaleOrder used by the first one.

I think simply changing it to let instead of var in the first screen might fix it. You can also try passing a copy of the object instead of a reference with saleOrder!.copy(), though I think your SaleOrder class will need to conform to the NSCopying protocol.

If you want to learn more about reference types you can read this topic Is Swift Pass By Value or Pass By Reference

Gabe
  • 316
  • 1
  • 5