Reputation: 6384
In my app I have a dialog box where the user enters some information into a UITextField. Before moving on I need to check that UITextField.text value equals something (the value is captured when the user clicks a submit button). However, my conditional (see below) keeps failing.
if (userAssignedName || userAssignedName.length > 0 || ![userAssignedName isEqualToString:@""]) {
//do something
} else {
[alertManager showAlert:@"You must enter a name for this OR"];
}
When I console log userAssignedName right before the conditional I get what I expect, nothing.
How can I check to make sure the string has value?
Upvotes: 0
Views: 200
Reputation: 318944
Replace this:
if (userAssignedName || userAssignedName.length > 0 || ![userAssignedName isEqualToString:@""]) {
with:
if (userAssignedName.length > 0) {
You don't want to use:
if (![userAssignedName isEqualToString:@""]) {
because if userAssignedName
is nil
, this if
statement will succeed when you want it to fail.
Upvotes: 0
Reputation: 7583
Well the solution is simple. Either of the 3 values returns a YES/true value.
![userAssignedName isEqualToString:@""]
This checks if your string is equal to an empty string. (which could be ur default of the textfield?) This is good.
userAssignedName.length > 0
This checks the chars in your string. This is also fine except you don't need it. It's mostly used for keeping a max number of characters in a textfield.
userAssignedName
This checks if the actual variable is instantiated. And doesn't and shouldn't involve the userinput in any way. If you remove this your check won't fail.
Solution:
if (/*userAssignedName.length > 0 ||*/ ![userAssignedName isEqualToString:@""])
{
//do something
}
else
{
[alertManager showAlert:@"You must enter a name for this OR"];
}
This should do the trick. And whether or not u use the comment or not is up to you.
Upvotes: 4