Aleksandar • Vacić

iOS bits and pieces

UITextField.text is not always there

If you have UITextField on the page and you need to validate is there something in it (so if yes you can save the input or something), you might do something like this:

1
2
3
if (![addNewCellTextField.text isEqualToString:@""]) {

}

However, this will fail if the field is never touched. That is, until your user taps the field and it gets focus, UITextField.text is nil. Which means that condition above yields true, which is not what you want.

Once it is touched though, this becomes an instance of NSString with value of @“”. Thus, always use:

1
2
3
if (addNewCellTextField.text != nil && ![addNewCellTextField.text isEqualToString:@""]) {

}

Watch out for this little trap hole.