# [Obj. C] How to tell if NSTextField is empty



## macmastah (Jul 31, 2008)

Hi,

I'm trying to write Objective C code that adds the numbers inputted in two text fields upon pushing the "Add" button. Also, the program should display an error message if one or both of the available text fields are not filled with anything. 

The code does add the two numbers in the textfields, but does not display the error message if nothing is inputted. It reads the empty text field as "0", therefore displaying the answer to "0+0" in the answer field. I also tried inputting a number into one text field and pressing "Add". As expected, this action displayed whatever the number was in the answer field.

I've posted the code below and would appreciate any help.

Thanks in advance!


```
@implementation OperatorClass
- (IBAction)add_button:(id)sender {
	//create two strings to get the inputs of the
        //two text fields which are int1_display, int2_display
	NSString *int_1 = [int1_display stringValue];
	NSString *int_2 = [int2_display stringValue];
	
	//create an empty string to compare the input fields with
	NSString *empty = nil;
	
	//If there's something in both fields, add the two inputs
	if (int_1 != empty && int_2 != empty) {
		answer = [int1_display floatValue] + [int2_display floatValue];
		[ans_display setFloatValue:answer];
	}
	//If there's nothing in both fields, display an error in the ans_display
	else if (int_1 == empty || int_2 == empty) {
		[ans_display setStringValue:@"Error!"];
	}
}
@end
```


----------



## Mikuro (Jul 31, 2008)

-stringValue will return an empty string if the field is empty, not nil, so you should change your code to compare the strings to @"", like so:


```
NSString *empty = @"";

//If there's something in both fields, add the two inputs
if (![int_1 isEqualToString:empty] && ![int_2 isEqualToString:empty]) {
	answer = [int1_display floatValue] + [int2_display floatValue];
	[ans_display setFloatValue:answer];
}
//If there's nothing in both fields, display an error in the ans_display
else {
	[ans_display setStringValue:@"Error!"];
}
```


----------



## macmastah (Aug 1, 2008)

Thanks alot! It worked perfectly.


----------

