Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

gizzerd91

macrumors newbie
Original poster
Jul 15, 2009
7
0
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];
	}
}
 
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.
 
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.

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.
 
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.

Actually, it's the same in Java.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.