Reputation: 288
This is just a visual scenario of what's actually happening.
I have an Object A in my View Controller1. Similarly, i have an ObjectB which is similar to the type of ObjectA, in my View Controller2.
Now, on click of a button, i assign ViewController2.ObjectB = ViewController1.ObjectA
(or self.ObjectA) from my 1st View Controller.
Now, the data passes successfully over to the ViewController2. But, when i perform some changes to ObjectB in ViewController2, the changes are reflected in ObjectA of ViewController1 as well.
This should not happen as the original data of ObjectA is then lost, which i need if user goes to and fro from ViewController1 to ViewController2 and vice-versa as i m always doing this ViewController2.ObjectB = ViewController1.ObjectA
on click of my button in ViewController1.
Anybody have any idea what's goin on ? Please help me out. It's driving me nuts :-(
Upvotes: 0
Views: 154
Reputation: 96
This is happening because your object is passed by reference, not by value. What you can do is to make a clone of your object instead of passing the object itself.
ViewController2.ObjectB = ViewController1.ObjectA.clone()
You have to implement clone function in ObjectA class that is going to create a new object from the current one, something like this
class MyClass {
let number: Int
init(number: Int) {
self.number = number
}
func clone() -> MyClass {
return MyClass(number: self.number)
}
}
If you want to know more look up https://developer.apple.com/swift/blog/?id=10 and https://www.raywenderlich.com/112027/reference-value-types-in-swift-part-1
Upvotes: 2