9

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?

oberbaum
  • 2,451
  • 7
  • 36
  • 52

4 Answers4

18

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
  • 1,554
  • 15
  • 20
  • Ivan, thanks that works nicely. Is there something like an inverse to isEqualToString, like a isnotEqualToString?? – oberbaum Jan 25 '10 at 13:23
  • How about: if ( ! [txtField.text isEqualToString:@""]) [txtField2 becomeFirstResponder]; – Mark Jan 25 '10 at 13:31
  • 1
    Yes, there's a way to do this. Not using a `isNotEqualTo:` method though. :) Added an example. – Ivan Karpan Jan 25 '10 at 13:31
9

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.

Warrior
  • 39,156
  • 44
  • 139
  • 214
Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • 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 Jan 25 '10 at 13:34
3

You must also check for nil

if([textfield.text isEqualToString:@""] || textfield.text== nil )

Only if the user clicks textfield you can check with isEqualToString else the textfield will be in the nil so its better you check for both the cases.

All the best

Warrior
  • 39,156
  • 44
  • 139
  • 214
0

We already have inbuilt method that return boolean value that indicates whether the text-entry objects has any text or not. Check that simple Solution with link

https://stackoverflow.com/a/25726765/3647325

Community
  • 1
  • 1
Gaurav Pandey
  • 1,953
  • 3
  • 23
  • 37