Swift class-property update

♀尐吖头ヾ 提交于 2019-12-04 07:09:42

问题


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



来源:https://stackoverflow.com/questions/41343905/swift-class-property-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!