-2

What is the syntax for checking if strings are identical?

in Java it is: string1.equals(string2);

but what is it in objective C?

Logan S.
  • 517
  • 1
  • 4
  • 15
  • I assume you don't actually want to check if they are identical or are the same string but actually want to check if they have the same contents. – David Schwartz Aug 01 '12 at 12:30
  • Yeah, just if they have the same contents, in my code I know that they are different values. – Logan S. Aug 01 '12 at 12:31

4 Answers4

2
NSString *String1, *String2;
if([String1 compare: String2] == NSOrderedSame)
    //They are the same

NSOrderedSame is defined as zero, so you can write

if(![String1 compare: String2])
    //Equals
Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
2

Use the specific string equality message

[string1 isEqualToString: string2]
waldrumpus
  • 2,540
  • 18
  • 44
1

You need to use isEqualToString.

 if ( [stringOne isEqualToString: stringTwo] ) { }
Mahesh
  • 34,573
  • 20
  • 89
  • 115
1

You'll need to use isEqualToString for the most accurate results. I've included a couple examples on how to use it.

NSString *aString = foo;
NSString *bString = bar;
if ([aString isEqualToString:bString]) {
    NSLog("Match");
}
else NSLog("No Match");
//No match.

NSString *aString = foo;
NSString *bString = bar;
if ([aString isEqualToString:@"foo"]) {
    NSLog("Double Foo!");
}
else NSLog("No Match");
//Double Foo!

NSString *aString = foo;
NSString *bString = bar;
if (![aString isEqualToString:bString]) {
    NSLog("No Match");
}
else NSLog("Match");
//No Match
Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
WhoaItsAFactorial
  • 3,538
  • 4
  • 28
  • 45