Get the text in string variable - iphone

I m confused with this from many days and couldn't understand how to resolve it.
I get some data from web server and assigning it to string variable.In assigning it if sometimes no data is available then that string is updated to null(NULL) and to nil(nil) sometimes to (null).So I m confused how to compare data in that variable.
if(stringvariable==NULL) // couldnot understand how to compare here ,with NULL or nil or (null)
{
// do something
}
When will the string variable change its state (to NULL or nil or (null)) ?

use this code..
if([stringvariable isEqualToString:#""] || [stringvariable isEqual:nil])
{
//Data not Found
}
else{
// Data not nil
}

You can check like
if([str length]>0 || ![str isEqualToString:#""]) {
// String is not empty
}

It should be :
if(![stringvariable isEqualToString:#""])
{
// stringvariable is not Empty.
}
else
{
// stringvariable is Empty.
}

Related

"If" statement not working with optional value

My problem is that I have some text fields that the user enters in numbers, the entered numbers then get saved to the corresponding variable.
However if the user doesn't enter a number and leaves it blank, the text field has a value of 'nil' and so would crash if unwrapped.
So I used an if statement to only unwrap if the contents of the test field are NOT nil, however this doesn't work. My program still unwraps it and crashes because the value is nil...
I don't understand how my if statement is not catching this.
On another note, how do I change my if statement to only allow Int values to be unwrapped and stored, strings or anything else would be ignored.
#IBAction func UpdateSettings() {
if CriticalRaindays.text != nil {
crit_raindays = CriticalRaindays.text.toInt()!
}
if EvapLess.text != nil {
et_raindays_lessthan_11 = EvapLess.text.toInt()!
}
if EvapMore.text != nil {
et_raindays_morethan_11 = EvapMore.text.toInt()!
}
if MaxWaterStorage.text != nil {
max_h2Ostore = MaxWaterStorage.text.toInt()!
}
if CarryForward.text != nil {
carry_forward = CarryForward.text.toInt()!
}
}
Your issue is that while the text exists, it doesn't mean toInt() will return a value.
Say the text was abc, CriticalRaindays.text != nil would be true but CriticalRaindays.text.toInt()! can still be nil, because abc cannot be converted to an Int.
The exact cause of your crash is likely that .text is equal to "", the empty string. It's not nil, but definitely not an Int either.
The better solution is to use optional binding to check the integer conversion and see if that passes, instead of merely the string existing:
if let rainDays = CriticalRaindays.text.toInt() {
crit_raindays = rainDays
}
If that doesn't compile, you possibly need to do Optional chaining:
if let rainDays = CriticalRaindays.text?.toInt()
Not on a Mac atm so can't test it for you but hope this makes sense!
Why not use an if let to unwrap on if the the text field's text is non-nil?
if let textString = self.textField.text as String! {
// do something with textString, we know it contains a value
}
In your ViewDidLoad, set CarryForward.text = "" This way it will never be nil
Edit:
To check if a textfield is empty, you can use this:
if (CarryForward.text.isEmpty) {
value = 10
}
else {
value = CarryForward.text
}

Why Does String Not Equal What Is Stored?

This is a simple, odd question...
if(tableViewNum == #"One") {
if ([drinkArray objectAtIndex:0] == currentDate) {
[updatedArray addObject:drinkArray];
NSLog(#"MADE THE ELSE1");
}
NSLog(#"MADE THE ELSE2");
}
else if (tableViewNum == #"Two") {
if ([[drinkArray objectAtIndex:0] isEqualToString:yesterdayDate])
[updatedArray addObject:drinkArray];
} else {
NSLog(#"MADE THE ELSE %#",tableViewNum);
[updatedArray addObject:drinkArray];
}
In the very first if statement I ask if tableViewNum == #"One"
But I don't go in that section of the if statement even though tableViewNum actually does equal #"One"
As you can see the very last NSLog all ways comes out as
MADE THE ELSE One
But if tableViewNum really equaled One it would have gone through the if statement not the else statement code...?????
You can't compare strings with the == operator. Use isEqualToString instead:
if([tableViewNum isEqualToString:#"One"]) {
// etc.
… and the same for the rest of the conditions. You're already doing it right in the second block.
To be more specific, you shouldn't compare ANY objects using ==. This compares just the pointers. Use [obj isEqual: otherObj] or with NSStrings isEqualToString: as described above.

Validation, UITextField

I am working on some simple form validation and need some assistance. Basically, I just need to make sure a UITextField doesn't have a '0' or no value whatsoever (nil) when a user runs a simple calculation. If the field does contain either/or a label will be changed to notify the user. Here is my statement:
if ([abc.text isEqualToString:#"0"] || [time.text isEqualToString:nil]) {
self.123.text = #"Please enter a time";
} else { whatever }
Currently the 123 label is outputting NaN if nothing is entered into the abc UITextField.
if (![abc.text isEqualToString:#"0"] &&
![time.text == nil])
{
self.123.text = #"Please enter a time";
}
else
{
whatever
}
Replace [time.text isEqualToString:nil] with [time.text isEqualToString:#""]
You are trying to compare string with a nil object, and since a nil object (nil) is not the same as an empty string (#""), it fails.

How to compare self.title to a string in Objective C?

What am I doing wrong in the below code? My if statement is missing something:
if ([self.title] = "Upcoming Events") {
} else {
}
Correct would be:
if( [self.title isEqualToString:#"Upcoming Events"] )
self.title is a pointer, you can only compare it to other pointers using == not their values.
if ([self.title isEqualToString:#"Upcoming Events"]) {
NSLog(#"True");
} else {
NSLog(#"False");
}
You just have to write like this:
if([self.title isEqualToString:#"Upcoming Events"])
{
}
else
{
}
also .... in a if you should use "==" instead of "=". When there is "==" it is checking if they are equal while if there is "=" it gives the first one the value of the second.

How to check if array is null or empty?

I want to check if my array is empty or null, and on base of which I want to create a condition for example.
if(array == EMPTY){
//do something
}
I hope I'm clear what I am asking, just need to check if my array is empty?
regards
if (!array || !array.count){
...
}
That checks if array is not nil, and if not - check if it is not empty.
if ([array count] == 0)
If the array is nil, it will be 0 as well, as nil maps to 0; therefore checking whether the array exists is unnecessary.
Also, you shouldn't use array.count as some suggested. It may -work-, but it's not a property, and will drive anyone who reads your code nuts if they know the difference between a property and a method.
UPDATE: Yes, I'm aware that years later, count is now officially a property.
you can try like this
if ([array count] == 0)
Just to be really verbose :)
if (array == nil || array.count == 0)
Best performance.
if (array.firstObject == nil)
{
// The array is empty
}
The way to go with big arrays.
if (array == (id)[NSNull null] || [array count] == 0) {
NSLog(#"array is empty");
}
Swift 3
As in latest version of swift 3 the ability to compare optionals with > and < is not avaliable
It is still possible to compare optionals with ==, so the best way to check if an optional array contains values is:
if array?.isEmpty == false {
print("There are objects!")
}
as per array count
if array?.count ?? 0 > 0 {
print("There are objects!")
}
There are other ways also and can be checked here
link to the answer
As nil maps to 0, which equals NO, the most elegant way should be
if (![array count])
the '==' operator is not necessary.
You can also do this kind of test using
if (nrow>0).
If your data object is not formally an array, it may work better.
null and empty are not the same things , i suggest you treat them in differently
if (array == [NSNull null]) {
NSLog(#"It's null");
} else if (array == nil || [array count] == 0) {
NSLog(#"It's empty");
}
if (array == nil || array.count == 0 || [array isEqaul [NSNull Null]])
In Swift 4
if (array.isEmpty) {
print("Array is empty")
}
else{
print("Array is not empty")
}