-1

The output of the code below is,

areEqual

areEqual

Can somebody explain why?

NSString *firstUserName = @"nick";
NSString *secondUserName = @"nick";

if (firstUserName  == secondUserName)
{
    NSLog(@"areEqual");
}
else
{
    NSLog(@"areNotEqual");
}

MyObject *object1 = [[MyObject alloc]init];
object1.identifier = @"1";
MyObject *object2 = [[MyObject alloc]init];
object2.identifier = @"1";

if (object2.identifier  == object1.identifier)
{
    NSLog(@"areEqual");
}
else
{
    NSLog(@"areNotEqual");
}
Community
  • 1
  • 1
ThE uSeFuL
  • 1,456
  • 1
  • 16
  • 29

1 Answers1

3

When you explicitly type @"nick" or @"1", it is a string literal that, for efficiency, the compiler is storing in the same memory location. If you created one of the strings in a different fashion, it would appear at a different memory location, such as if you built up the first string by concatenating two strings together.

Generally comparing two strings in this way is not what you want to do. Usually you want to compare the two strings for equality, and rarely want to know if they actually point to the same memory address. You should use isEqual: or isEqualToString: instead.

Gavin
  • 8,204
  • 3
  • 32
  • 42