Swift class-property update

2019-03-06 04:27发布

问题:

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?

回答1:

You can use mutableCopy() with your object but for that your custom class need to extends from NSObject and its return type is Any so you need to explicitly type cast its result to your CustomClass.

targetVC.reservation = self.reservation!.mutableCopy() as! YourCustomClass


回答2:

Classes are ref type. so whenever you are assigning the targetVC.reservation!.id = id it is also changing the self.reservation.id value. Both pointing to the same object. If you don't want to change the reservation.id value when targetVC.reservation!.id changes you can create copy of your class using mutableCopy but your class needs to extends NSObject as @Nirvad D said or you can use Structures which is value types.

You can go to documentation for further reading Classes and Structures