Swift class-property update

2019-03-06 04:14发布

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?

2条回答
欢心
2楼-- · 2019-03-06 04:58

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
查看更多
Lonely孤独者°
3楼-- · 2019-03-06 05:01

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

查看更多
登录 后发表回答