"simple" (?) string-comparison problem

Discussion in 'iOS Programming' started by Danneman101, Feb 25, 2009.

  1. macrumors 6502

    Joined:
    Aug 14, 2008
    #1
    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?

    Code:
    	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];
    
    	}
    
     
  2. macrumors 6502a

    Joined:
    Oct 24, 2008
    Location:
    Cambridge
    #2
    == compares pointers, not the strings themselves. You want:

    Code:
    [myTitle isEqualToString:@"HELLO"]
    which returns true if the strings are equal.
     
  3. Guest

    caveman_uk

    Joined:
    Feb 17, 2003
    Location:
    Hitchin, Herts, UK
    #3
    The same is true of all objects not just strings. You cannot compare the contents using '==' you must use an isEqualToxxxx: method.
     
  4. thread starter macrumors 6502

    Joined:
    Aug 14, 2008
    #4
    Thanks you guys :) I guess Im still stuck in the world of C++/C#. Wow, objc is VERY different..:confused:
     
  5. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #5
    You can compare strings using == in C++/C#? :confused:
     
  6. macrumors G4

    Joined:
    Jan 5, 2006
    Location:
    Redondo Beach, California
    #6
    Not that different. In plain old Ansi C the == thing would fail for the same reason.
     
  7. macrumors regular

    Joined:
    Jun 10, 2008
    #7
    If you overload the '==' operator, you can. :)
     

Share This Page