If "a == b" is false when comparing two NSString objects

I have a class with an available method that returns an NSString when called.

 [MyClass getMyString] 

The string variable in this class is actually assigned to the didSelectRowAtIndexPath: table part as follows:

 myString = cell.textLabel.text; 

When I get a string by calling this method, I assign it to another string in the class that called it, and compare it to the string I defined

 NSString *mySecondString; mySecondString = @"my value"; if(mySecondString == myString){ i = 9; } 

I went through the code and every time he evaluates the if statement, it skips right past i=9 and goes on to the next else if . Why should it be? Why don't they value the same value? If you hover over each of the values โ€‹โ€‹during debugging, they will show that they have the same value, but for some reason the code does not do what I expect and assign 9 i .

Any thoughts?

+6
source share
5 answers

You assume that the C == operator performs string equality. This is not true. It performs pointer equality (when calling pointers). If you want to run a true string equality test, you need to use the -isEqual: method (or the -isEqualToString: specialization when you know that both objects are strings):

 if ([mySecondString isEqualToString:myString]) { i = 9; } 
+17
source

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

 if (if([mySecondString isEqualToString:myString]) { .... } 
+3
source

you cannot use '==' to compare two NSString

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

+2
source

You cannot compare two strings using "==", this is for int and other values. you can use the code below to compare two lines

if ([Firststring isEqualToString: Secondstring]) {

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

}

+1
source

This is the basic concept of a pointer, you're out. (YES, myString and mySecondString are pointers to a string).

Now if(mySecondString == myString) will go TRUE only if both pointers point to the same location. (Which they will not be in most cases)

You should do if ([mySecondString isEqualToString:myString]) , which will compare your and string content for equality.

+1
source

Source: https://habr.com/ru/post/904282/


All Articles