Home > Back-end >  One instance of a class changing property value but other instance doesn't get updated with the
One instance of a class changing property value but other instance doesn't get updated with the

Time:08-09

Here as you can see class SameData there are two instances data1 and data2. If I change data2 instances userName that is stored in the class properties it doesn't get updated in data1 instance of the same class.

In swift class should get updated in all instances when properties change in one instance. But why this is happening?

Code:

class SameData { 
var userName = "Anonymous" 
} 
var data1 = SameData()
var data2 = SameData() 
data2.userName = "Not Anonymous"
print(data2.userName) 
print(data1.userName)

Result:

"Not Anonymous\n"
"Anonymous\n"

As this is a class and one instance is changing userName then all the instances of the class should adopt the change am I right? So, the result should be something like this.

Expected Result:

"Not Anonymous\n"
"Not Anonymous\n"

CodePudding user response:

in the class properties

These aren't class properties. These are just instance properties, on two different instances. Naturally, changing one doesn't change the other. That's the whole point of instances. They're separate instances. These are just instance properties with default values, similar to writing:

class SameData { 
    var userName: String

    init() {
        self.userName = "Anonymous" 
    }
} 

Class properties are marked with class (or similarly, static, which is roughly equivalent to class final).

That said, marking a username as a class constant doesn't really make sense. Presumably, each user should have their own username, and they should be independent. You should add more detail on the kind of data you're trying to model, so we can give more concrete advice on thow to handle it.

CodePudding user response:

I will explain as an answer, since I can't fit it into comment.

  • In var data1 = SameData() the SameData() is the object, and data1 is like a finger pointing to that object.
  • Then when you say var data2 = SameData(): you create a second object, and point a finger data2 to that object.

So you have 2 objects, and 2 fingers pointing to each object respectively, neither object knows about existence of the other.

Now, if you do var data2 = data1, you are not creating a new object, instead you are pointing another finger data2 to the same object you previously created. So here you have 2 fingers pointing to the same object.

Hence in first case, by changing data1 you are changing the first object, but the second object (to which data2 points) remains intact.

In second case, by changing data1, you are changing the only object you have. And since both fingers point to that same object, they both see the change.

  • Related