0

As per this post: Understanding NSString comparison it will give different results but when I tried this with different scenarios as mentioned below it gave me same result.

I just want to know when '==' and 'isEqualToString:" gives different results. For me it is giving same results.

I tried below mentioned ways:

NSString *str1 = @"Hello!";
NSString *str2 = @"Hello!";

if(str1 == str2){
}

if([str1 isEqualToString:str2]){
}

=================

NSString *str1 = [[NSString alloc] initWithString:@"Hello!"];
NSString *str2 = [[NSString alloc] initWithString:@"Hello!"];

if(str1 == str2){
}

if([str1 isEqualToString:str2]){
}

=================

ClassA *obj1 = [[ClassA alloc] initWithString:@"Hello!"];
ClassA *obj2 = [[ClassA alloc] initWithString:@"Hello!"];
// The above "initWithString:" is the custom initializer for ClassA.

if(obj1.str == obj2.str){
}

if([obj1.str isEqualToString:obj2.str]){
}

================

Each of the above ways gives me same result. As per I know till now '==' compares object reference and 'isEqualToString:' compare the values of the objects.

Any detail answer with example would be very helpful!

Community
  • 1
  • 1
Dharmesh Siddhpura
  • 1,610
  • 12
  • 22
  • I saw this post before posting my question and the steps mentioned in there didn't worked. So I have posted this question with different scenarios. – Dharmesh Siddhpura Sep 07 '16 at 20:18
  • The behavior in that question is outdated due to tagged pointers being used in strings on 64-bit devices. There are more cases now where `==` and `isEqualToString:` behave the same. They will basically always be the same for short strings like the ones you are using in your examples. – dan Sep 07 '16 at 20:22
  • @dan: So in which case '==' and 'isEqualToString:' gives different result? Can you please elaborate this? – Dharmesh Siddhpura Sep 07 '16 at 20:24
  • 2
    Create two strings by doing `NSString *str = [[NSString alloc] initWithFormat:@"%@", @"Hello!Hello!Hello!Hello!Hello!"];` and compare them. – dan Sep 07 '16 at 20:31
  • @dan: thanks for your kind answer. Here if I initialize the string with 'initWithFormat:' it gives different result. But if we initialize string with 'initWithString:' it gives same result. Can you plz give me some idea on this? – Dharmesh Siddhpura Sep 07 '16 at 20:50
  • I'd assume the compiler is able to do some optimization when you use `initWithString:` with a constant string and reduce it to the same as in your first example. – dan Sep 07 '16 at 20:55
  • Alright. Got it. I appreciate for elaborating it in details. It helped me and hope this help others. – Dharmesh Siddhpura Sep 07 '16 at 21:00

0 Answers0