Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone / objective-c how to check to see if a textfield is empty

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?

like image 865
oberbaum Avatar asked Jan 25 '10 13:01

oberbaum


People also ask

How do I check if a string is empty in Objective C?

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.

How do I know if my Uitextfield is empty?

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


3 Answers

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];
like image 181
Ivan Karpan Avatar answered Oct 20 '22 01:10

Ivan Karpan


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.

like image 38
Vladimir Avatar answered Oct 19 '22 23:10

Vladimir


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

like image 25
Warrior Avatar answered Oct 20 '22 01:10

Warrior