So I have to pass instance of my custom class from one UIViewController
to another:
targetVC.reservation = self.reservation!
print(self.reservation!.id, "before")
targetVC.reservation!.phoneNumber = self.phoneTextField.text!.phoneToString()
targetVC.reservation!.id = id
print(self.reservation!.id, "after")
My problem is that self.reservation!.id
is also changed: "before" it is ""
, and "after" it is id
. Why does it happen and how to avoid this?
You can use
mutableCopy()
with your object but for that your custom class need to extends fromNSObject
and its return type isAny
so you need to explicitly type cast its result to yourCustomClass
.Classes are ref type. so whenever you are assigning the
targetVC.reservation!.id = id
it is also changing theself.reservation.id
value. Both pointing to the same object. If you don't want to change thereservation.id
value whentargetVC.reservation!.id
changes you can create copy of your class usingmutableCopy
but your class needs to extendsNSObject
as @Nirvad D said or you can useStructures
which is value types.You can go to documentation for further reading Classes and Structures