views:

947

answers:

2

I have a typical textfield in an iphone app, and in ViewWillAppear I would like to do a little logic using the text in the text field.

If txtField.text is empty, I would like the next textfield, txtField2 to be selected for typing.

I am trying to achieve this through :

if (txtField.text != @"") [txtField2 becomeFirstResponder];

but after some testing, txtField.text (whilst empty), will still not register as being equal to @"" What am I missing?

+5  A: 

Hey norskben!

When you compare two pointer variables you actually compare the addresses in memory these two variables point to. The only case such expression is true is when you have two variables pointing to one object (and therefore to the very same address in memory).

To compare objects the common approach is to use isEqual: defined in NSObject. Such classes as NSNumber, NSString have additional comparison methods named isEqualToNumber:, isEqualToString: and so on. Here's an example for your very situation:

if ([txtField.text isEqualToString:@""]) [txtField2 becomeFirstResponder];

If you want to do something if a NSString is in fact not empty use ! symbol to reverse the expression's meaning. Here's an example:

if (![txtField.text isEqualToString:@""]) [txtField2 becomeFirstResponder];
Ivan Karpan
Ivan, thanks that works nicely. Is there something like an inverse to isEqualToString, like a isnotEqualToString??
norskben
How about:if ( ! [txtField.text isEqualToString:@""]) [txtField2 becomeFirstResponder];
Mark Thalman
Yes, there's a way to do this. Not using a `isNotEqualTo:` method though. :) Added an example.
Ivan Karpan
+3  A: 

You must check either:

if (txtField.text.length != 0)

or

if ([txtField.text isEqualToString:@"")

Writing your way: (txtField.text != @"") you in fact compare pointers to string and not their actual string values.

Vladimir
I've fired a quick answer first and then added some explaining... :) Checkin length is another good way though. Especially because zero int value is treated as false. `if (!txtField.text.length)` is probably the 'shortest' approach.
Ivan Karpan