iOS NSString from UITextField - checking value - ios

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?

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.

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.

Related

I want to add the values of 2 UILabels together to display the results in a separate UILabel

//un-wrap string in label and cast to Int
let made = ShotsMadeLabel.text?.toInt() //shots made Int
let miss = ShotsMissedLabel.text?.toInt() //shots missed Int
// check to see if both values are not equal to zero
// add values and display answer (ans)in TotshotShotsMadelabel
if (miss != 0) || (made != 0){
var ans = made! + miss!
TotalShotsMadeLabel.text = "\(ans)"
println(ans) // check results
per request provided clarity to my question.. please let me know if there is a better way to do this..
Your code looks good but it fails to cover the case where one of the labels' text is empty or not a number. In that case, made or miss can be nil and you will crash when you force-unwrap it (with the exclamation mark).
So, you'd need to add another level of safety:
if (miss != 0) || (made != 0) {
if (miss != nil) && (made != nil) {
var ans = made! + miss!
}
}
But the truth is that you should not be doing this in the first place. Do not store state in a view like a label! This whole business of extracting the text from a label and turning it into a number is just wrong. You should have model variables in your code that are actual numbers, maintaining this information. When they change, change the labels. And that way, you can just add them. MVC, model-view-controller. Do not use View as Model, which is what you are doing.

Method To Delete 2nd Label, Then First Label, Not Functioning Correctly

I know I am missing something obvious, but I just cannot see it. This method is meant to compare the text of a label to the text of a text box, and then delete the text. So if the 1st label reads "Puppy" and the 2nd label reads "Kittens," and the text box says "Kittens," the method should delete the text of the 2nd label and leave the 1st label's text. If the 2nd label is blank, then the method should delete the text of the 1st label.
But no matter how I mess with the method, either it deletes the 2nd label but not the 1st, deletes both of them, or deletes neither of them. Here's what I've tried
(lblFabric1 is the 1st label, lblFabric2 is the 2nd label, txtType is the text box):
-(IBAction)btnDelete:(id)sender
{
if ((self.lblFabric2.text== self.txtType.text))
{
self.lblFabric2.text = #"";
}
else if ((self.lblFabric2.text != self.txtType.text))
{
self.lblFabric1.text=#"";
}
}
It deletes the 2nd label, but not the 1st label. If I try to set the "Else if" to:
else if ((self.lblFabric2.text==#""))
it gives me an error (""Direct comparison of a string literal has undefined behavior.") Am I just going about this the wrong way? What am I missing?
You should not use == or != for string comparison in Objective C. You need to use the isEqualToString or isEqual method.
if (([self.lblFabric2.text isEqualToString:self.txtType.text]))
When you use == or != you are comparing the pointers where the strings are stored.
To compare NSStrings use:
if ([myString1 isEqualToString:myString2])
Documentation
Compairing String literals using == is not guaranteed to behave as you might expect. Use isEqual: or isEqualToString: instead.
See http://nshipster.com/equality/.
When you are comparing NSStrings with == what you are actually comparing are two memory addresses and that is not what you are really intended for. You want to compare the values of two strings what == operator is not suitable for and thus you are getting the warning
Direct comparison of a string literal has undefined behavior.
To compare the values of NSStrings you should use isEqualToString: method. You could have also use isEqual: method derived from NSObject class but that is not suitable for Unicode comparison. So isEqualToString: is always the safest bet.
After using isEqualToString: your code should look something like:
-(IBAction)btnDelete:(id)sender
{
if ([self.lblFabric2.text isEqualToString:self.txtType.text])
{
self.lblFabric2.text = #"";
}
else
{
self.lblFabric1.text=#"";
}
}

iPhone string comparison strange issue in iOS 6

I used to compare the text entered in a txt field as below,
if ([myTextfield.text isEqualToString: #""])
{
// success code
}
else
{
// my code
}
in iOS 7 this check works perfectly. If nothing entered in to the text field, condition is success. But in iOS 6 if the field is blank, this condition always false and moves to the else block.
So i did like,
if (myTextfield.text.length == 0)
{
// success code
}
else
{
// my code
}
This works fine, and I just wanted to know what is wrong in my first method.
If myTextfield.text is nil, [myTextfield.text isEqualToString: #""] will fail because messaging nil returns nil (or 0, NO as appropriate).
In the second case you have, you are checking for == 0, so even if the string is nil you will still get a positive result.
In iOS7, untouched UITextFields return nil, whereas in previous iOS versions they return an empty string. Touched UITextFields in both cases should return an empty string.
(Did you ask the question in reverse mistaking iOS6 w 7? If not, I'd also make sure the text field is hooked up properly since a touched iOS7 text field could return an empty string while an unsynthesized iOS6 text field could return NULL since iOS6 is especially strict in this way.)

test if object is in an array of objects

I know I'm overlooking something easy, but I am using
if (textField == self.nameTextField || textField == self.ageTextField || textField == ...)
when ideally I'd like to use something that allows the textField to be compared to an array of allowed (named) textField objects.
I've tried to pseudocode what I think the solution would look like a couple of times, I just don't know what I'm doing. Can anyone point me in the right direction?
Just check like:
if([textFieldArray containsObject:textField])
{
//do stuff here
}
Here textFieldArray is the array which holds all textFields.
If the textField object is in the textFieldArray, it'll return true.
Firstly add all references of UITextFields in NSArray.
Now use containsObject in NSArray to check if exists
BOOL contains = [yourArrayofTextFields containsObject:textField];
if(contains)
// contains
else
// not contains

iOS Compare Value of Label

I'm using a label to display the string result of function. However I have a class variable that stores the previous result and I need to update that variable in different ways depending on different conditions. The code I wrote is
if(displayPassword.text == #"Memorable")
{
prevpass = [newPassword returnPassword];
}
else
{
prevpass = displayPassword.text;
}
However it always jumps to the else as it seems to show under debugging that displayPassword.text is always empty depsite it showing a value.
You can only use == to compare scalar values. A string is an object. You need to use the isEqual: or isEqualToString: method instead.
if([displayPassword.text isEqualToString:#"Memorable"]) {

Resources