I am facing issue to clone an object in swift 3. I want to duplicate/clone an object then want to modify it's value so that modification doesn't reflect on the actual object. Here is what I did.
let patientInformation = PatientInformationController.shared().pateintInformation.copy() as! PateintInformation
patientInformation.firstName = "Some Name"
The above line actually not just modifying the local copy but also affecting the actual PatientInformationController.shared().pateintInformation.firstName The PateintInformation conforms to NSCopying protocol.
I have checked memory addresses for both objects (actual and copy), they are different.
In PatientInformation class:
required public init(instance: PateintInformation) {
self.firstName = instance.firstName
}
public func copy(with zone: NSZone? = nil) -> Any {
return PateintInformation(instance: self)
}
You've incorrectly implemented conformance of class to NSCopying protocol. You have same references in copy and in object, that's why changes happens. You can look here how to do it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.