Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two NSStrings

In my app there is a mechanism that requires that at a certain point two NSStrings will be the same to do something; for some reason when I compare the two, even when they are the same, it still doesn't recognize that. The code is something like this:

NSString * aString = [self someMethodThatGetsAString];

NSString * bString;

BOOL areStringsTheSame = NO;

while (areStringsTheSame != YES) {

       bString = [self someMethodThatTakesNSStringsFromAnArrey];
       if (bString == aString) {
             areStringsTheSame = YES;
       { }

I even inserted an NSLog() and made sure that at a certain point they were the same (and as far as I know this is what == stands for...), but still it didn't get into the if to change the BOOL value.

Is there another way to do this comparison? Am I missing something?

like image 780
Ohad Regev Avatar asked Aug 06 '11 21:08

Ohad Regev


People also ask

How can I compare two Nsstrings?

To compare two strings equality, use isEqualToString: . BOOL result = [firstString isEqualToString:secondString]; To compare with the empty string ( @"" ), better use length .

What is Nsstring?

A static, plain-text Unicode string object which you use when you need reference semantics or other Foundation-specific behavior.

How do I check if a string contains a substring in Objective C?

Checking the string contains another To check if a string contains another string in objective-c, we can use the rangeOfString: instance method where it returns the {NSNotFound, 0} if a 'searchString' is not found or empty (""). Output: string contains you!


2 Answers

You can use the method isEqualToString::

if ([bString isEqualToString:aString])

== compares the references (addresses of) the strings, and not the value of the strings.

like image 174
MByD Avatar answered Oct 25 '22 01:10

MByD


This approach worked for me:

if ([firstString compare:secondString] == NSOrderedSame) {
    //Do something when they are the same
} else {
    //Do something when they are different
}
like image 40
xSolver Avatar answered Oct 25 '22 01:10

xSolver