The following code is a snippet I took from a lecture on objective-c which is meant to illustrate the differences between identity and equality in objective-c.
There are a few things I don't understand about it and since one part of the code relates to the other, I have copied the code in full.
The first part:
// test for object identity:
NSString *a = @“Peter”;
NSString *b = @“Peter";
BOOL identical = a == b; //YES
I don't understand how the objective-c compiler concludes that object a is identical to object b. I realise that they both contain the exact same string, namely "Peter", but I would have thought that since a and b are separate objects, that they would each have unique memory addresses as such, and I would have thought that the = operator then would be testing that rather than testing if a and b contain the same string.
Part 2:
// test for string equality: will return YES
NSString *aName = @"Peter";
NSMutableString *anotherName =
[NSMutableString stringWithString:@"P"];
[anotherName appendString:@"eter"];
BOOL equal = [aName isEqualToString:anotherName]; //YES
BOOL identical = (aName == anotherName); //NO
I understand this code to have first created an object aName
which is "Peter" and anotherName
which is "P".
The next bit I don't get. My first problem understanding this: "eter" is appended to anotherName in a standalone statement before we test for equality but as far as I understand it, even though we say
[anotherName appendString:@"eter"];
we have not stored this result anywhere so that when we ask if anotherName
is equal to the string in aName
, I would have thought that anotherName
was still just "P". And my second problem understanding this part 2 of the code, is that I don't see how they are equal. (Similar to my problem in Part 1.)
And again I do not know why the last line of code which tests for identity would return NO for not equal.