开发者

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 test开发者_Go百科ing, txtField.text (whilst empty), will still not register as being equal to @"" What am I missing?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜