Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField : testing text property for empty string or nil or null doesn't work

I got this weird problem testing for empty (or null) text property. Here my setup : I got a view with 6 textfield in it and here the code I use to go thru those field (loaded in a NSMutable Array)...

NSEnumerator *portsEnumerator = [appliancePorts objectEnumerator];
UITextField *tmpField;
newSite.port = [NSMutableArray array];
while (tmpField =[portsEnumerator nextObject]) {
    NSLog(@"value:%@",tmpField.text);
    if (![tmpField.text isEqualToString:nil]) {
        [newSite.port addObject:(NSString *)tmpField.text];
    }
}

When I'm in this interface and type some text in the first two field and "just" tab the remaning field and it the "Done" button here's what I got from GDB output:

2010-08-10 20:16:54.489 myApp[4883:207] value:Value 1

2010-08-10 20:16:58.115 myApp[4883:207] value:Value 2

2010-08-10 20:17:02.002 myApp[4883:207] value:

2010-08-10 20:17:13.034 myApp[4883:207] value:

2010-08-10 20:17:15.854 myApp[4883:207] value:

2010-08-10 20:17:17.762 myApp[4883:207] value:

I know that if I test for empty string it should work because the text property when dump to the console show this :

UITextField: 0x5d552a0; frame = (20 8; 260 30); text = ''; clipsToBounds = YES; opaque = NO; tag = 1; layer = CALayer: 0x5d54f20

But the REAL problem begin when I go back the view, enter some text in the same first two field and it the "Done" button right after (not going thru the other field so they don't get any focus). This is again the GDB output...

2010-08-10 20:23:27.902 myApp[4914:207] value:Value 1

2010-08-10 20:23:31.739 myApp[4914:207] value:Value 2

2010-08-10 20:23:34.523 myApp[4914:207] value:(null)

2010-08-10 20:23:56.443 myApp[4914:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 2'

So, the obvious problems is that first the isEqualtoString:nil doesn't work and second, how come this text change from '' to null in just of matter of putting the focus on the field.

So, is there a better way to test for empty field ?

Thanks!

like image 200
Steve S. Avatar asked Aug 11 '10 00:08

Steve S.


1 Answers

I tend to use

if (![tmpField.text length])

This will miss it out if it either nil or @"". i.e. it finds the length of the string, and if it is 0 (which would be the case if the string were empty or nil) it does not execute the IF command.

like image 87
Helen Avatar answered Oct 31 '22 02:10

Helen