If “a == b” is false when comparing two NSString objects

前端 未结 5 1634
梦毁少年i
梦毁少年i 2020-11-27 23:21

I have a class with an accessible method that passes back an NSString when called.

[MyClass getMyString]

The string variable

相关标签:
5条回答
  • 2020-11-27 23:56

    You are comparing pointers to strings, rather than the strings themselves. You need to change your code to

    if (if([mySecondString isEqualToString:myString]) {
        ....
    }
    
    0 讨论(0)
  • 2020-11-27 23:58

    You can not compare the two string using "==" this is for int and other values. you can use below code for the comparing two string

    if ([Firststring isEqualToString:Secondstring]) {

      NSLog(@"Hello this both string is same ");
    

    }

    0 讨论(0)
  • 2020-11-28 00:00

    you can not use '==' to compare two NSString

    you should to use [NSString isEqualToString:(NSString*)] to compare two string

    0 讨论(0)
  • 2020-11-28 00:05

    It's a basic concept of pointer, you are missing. (YES, myString and mySecondString are pointers to the string).

    Now, if(mySecondString == myString) will go TRUE only if, both the pointers are pointing to the same location. (Which they won't in most cases)

    You should be doing if ([mySecondString isEqualToString:myString]), which will be comparing your both string's content for equality.

    0 讨论(0)
  • 2020-11-28 00:20

    You're assuming that the C == operator does string equality. It doesn't. It does pointer equality (when called on pointers). If you want to do a real string equality test you need to use the -isEqual: method (or the specialization -isEqualToString: when you know both objects are strings):

    if ([mySecondString isEqualToString:myString]) {
        i = 9;
    }
    
    0 讨论(0)
提交回复
热议问题