Swift class-属性更新
Swift class-property update
所以我必须将自定义 class 的实例从一个 UIViewController
传递到另一个:
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")
我的问题是 self.reservation!.id
也发生了变化:“before”是 ""
,而“after" 是 id
。为什么会发生这种情况以及如何避免这种情况?
类 是 ref 类型。因此,每当您分配 targetVC.reservation!.id = id
时,它也会更改 self.reservation.id
值。两者都指向同一个对象。如果您不想在 targetVC.reservation!.id
更改时更改 reservation.id
值,您可以使用 mutableCopy
创建 class 的副本,但您的 class 需要扩展 NSObject
正如@Nirvad D 所说,或者您可以使用 Structures
这是值类型。
你可以去文档进一步阅读类和结构
您可以将 mutableCopy()
与您的对象一起使用,但为此您的自定义 class 需要从 NSObject
扩展并且它的 return 类型是 Any
所以您需要明确地将其结果类型转换为 CustomClass
.
targetVC.reservation = self.reservation!.mutableCopy() as! YourCustomClass
所以我必须将自定义 class 的实例从一个 UIViewController
传递到另一个:
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")
我的问题是 self.reservation!.id
也发生了变化:“before”是 ""
,而“after" 是 id
。为什么会发生这种情况以及如何避免这种情况?
类 是 ref 类型。因此,每当您分配 targetVC.reservation!.id = id
时,它也会更改 self.reservation.id
值。两者都指向同一个对象。如果您不想在 targetVC.reservation!.id
更改时更改 reservation.id
值,您可以使用 mutableCopy
创建 class 的副本,但您的 class 需要扩展 NSObject
正如@Nirvad D 所说,或者您可以使用 Structures
这是值类型。
你可以去文档进一步阅读类和结构
您可以将 mutableCopy()
与您的对象一起使用,但为此您的自定义 class 需要从 NSObject
扩展并且它的 return 类型是 Any
所以您需要明确地将其结果类型转换为 CustomClass
.
targetVC.reservation = self.reservation!.mutableCopy() as! YourCustomClass