I'm new to object-oriented programming, and one concept that has been taking me a while to grasp is immutability. I think the light bulb went off last night but I want to verify:
When I come across statements that an immutable object cannot be changed, I'm puzzled because I can, for instance, do the following:
NSString *myName = @"Bob";
myName = @"Mike";
There, I just changed myName, of immutable type NSString. My problem is that the word, "object" can refer to the physical object in memory, or the abstraction, "myName." The former definition applies to the concept of immutability.
As for the variable, a more clear (to me) definition of immutability is that the value of an immutable object can only be changed by also changing its location in memory, i.e. its reference (also known as its pointer).
Is this correct, or am I still lost in the woods?
NSString
, it is a "pointer to andNSString
", which is not immutable. I know nothing of objective C, but I'm guessing in your example that@"Mike"
is creating a new instance ofNSString
and assigning it to the pointer,myName
. So you haven't changed the object thatmyName
was pointing to, just what it was pointing to.