Newbie trouble with if statements

Discussion in 'iOS Programming' started by gizzerd91, Jul 15, 2009.

  1. gizzerd91 macrumors newbie

    Joined:
    Jul 15, 2009
    #1
    I'm a seasoned java programmer with no experience in C or C++ trying to make the jump to Obj-C (what a nightmare), and after a couple days of reading docs, I got started writing my first app, as per the excellent tutorial found here. When the user taps a button, the program updates a label from the contents of a text box. I got done with it, and am trying to add in a simple if statement, to only allow the user to change the label if the text in the text box is not a certain string, in this case "boring". But the program goes ahead as though the if isn't even there. What am I doing wrong here?

    I included the two different methods I have tried because neither of them has worked, and as long as I'm here I might as well.

    Method 1:
    Code:
    - (IBAction)click:(id)sender;
    {
    	NSString *newText = [textField text];
    	if (newText != @"boring") {
    		[label setText:newText];
    	}
    }
    Method 2 (I saved "boring" in a variable):
    Code:
    - (IBAction)click:(id)sender;
    {
    	NSString *newText = [textField text];
    	NSString *dontCopy = @"boring";
    	if (newText != dontCopy) {
    		[label setText:newText];
    	}
    }
     
  2. North Bronson macrumors 6502

    Joined:
    Oct 31, 2007
    Location:
    San José
    #2
    The first thing I would try is to replace:

    Code:
    if (newText != @"boring")
    with

    Code:
    if ([newText isEqualToString: @"boring"] == NO)
    and see if that makes a difference.

    When you are dealing with Foundation and Objective-C objects, there are appropriate times to compare equality (the two objects are equal, but not necessarily pointing to the same memory) with ==, but you should usually be better off using the isEqual: family of methods.

    Check up the documentation on isEqualToString: and see if this helps at all.
     
  3. Saladinos macrumors 68000

    Saladinos

    Joined:
    Feb 26, 2008
    #3
    Indeed. Your if statement is comparing objects, which are pointers to memory locations. The comparison operator checks if they point to the same space in memory. The isEqual: selector does the content comparison.

    Welcome to the world of C.
     
  4. eddietr macrumors 6502a

    Joined:
    Oct 29, 2006
    Location:
    Virginia
    #4
    Actually, it's the same in Java.
     
  5. gizzerd91 thread starter macrumors newbie

    Joined:
    Jul 15, 2009

Share This Page