ThE uSeFuL February 2016

Comparing NSString

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");
}

Answers


Gavin February 2016

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.

Post Status

Asked in February 2016
Viewed 3,962 times
Voted 9
Answered 1 times

Search




Leave an answer