PDA

View Full Version : "simple" (?) string-comparison problem




Danneman101
Feb 25, 2009, 05:15 AM
Ive got a little codesnippet where Im trying to compare a string with another.

Even though writing out the myTitle-variable in the alertbox will in fact display the string ("HELLO") that Im comparing it with (tried it by removing the if-statement and just executing the alert-box), the if-statement wont equate myTitle to the string.

Is this due to some inconsistency between datatypes, perhaps? I mean, they are both strings, arent they, and thus should be comparable?


NSString *myTitle = level2ViewController.title;
if(myTitle == @"HELLO")
{
// Display alert
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Title:" message:myTitle delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[myAlert show];
[myAlert release];

}



jnic
Feb 25, 2009, 05:23 AM
== compares pointers, not the strings themselves. You want:

[myTitle isEqualToString:@"HELLO"]

which returns true if the strings are equal.

caveman_uk
Feb 25, 2009, 06:37 AM
The same is true of all objects not just strings. You cannot compare the contents using '==' you must use an isEqualToxxxx: method.

Danneman101
Feb 25, 2009, 04:20 PM
Thanks you guys :) I guess Im still stuck in the world of C++/C#. Wow, objc is VERY different..:confused:

dejo
Feb 26, 2009, 12:10 AM
Thanks you guys :) I guess Im still stuck in the world of C++/C#. Wow, objc is VERY different..:confused:
You can compare strings using == in C++/C#? :confused:

ChrisA
Feb 26, 2009, 01:17 AM
Thanks you guys :) I guess Im still stuck in the world of C++/C#. Wow, objc is VERY different..:confused:

Not that different. In plain old Ansi C the == thing would fail for the same reason.

kalimba
Feb 26, 2009, 01:41 PM
You can compare strings using == in C++/C#? :confused:
If you overload the '==' operator, you can. :)