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?
You can check if [string length] == 0 . This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.
You can use this block of code. if textField. text?. isEmpty { //Return true if the textfield is empty or false if it's not empty. }
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];
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With