Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS can't check if object is null

Tags:

ios

ios5

So I have the following code:

- (IBAction)doSomething
{
if (txtName.text != (id)[NSNull null] || txtName.text.length != 0 ) {
    NSString *msg = [[NSString alloc] initWithFormat:@"Hello, %@", txtName.text];
    [lblMessage setText:msg];
}

}

txtName is an UITextField, what I'm doing wrong? I'm trying to display some text only when the user types something in the box.

Best Regards,

like image 831
Uffo Avatar asked Nov 27 '11 21:11

Uffo


3 Answers

Text in a text field is a NSString instance or nil value, it is never equal to the instance of NSNull class (which is not the same as nil). So as 1st comparison is always true then the whole if-condition evaluates to true and message appears.

You could correct your if condition to

if (txtName.text != nil && txtName.text.length != 0 )

or, as sending length message to the nil will return 0 anyway just have

if (txtName.text.length != 0 )

although I usually use the 1st option with 2 comparisons

like image 93
Vladimir Avatar answered Sep 19 '22 03:09

Vladimir


if (txtName.text != (id)[NSNull null] || txtName.text.length != 0 ) {

Read it as "If the text is null or the length is not 0"

txtName.text is never nil (you can just compare against nil for a null check, by the way) - the text box always holds some text, even if it's empty. So the first disjunct is always true, and the box will always appear.

like image 26
Adam Wright Avatar answered Sep 21 '22 03:09

Adam Wright


I got the same problem like you. This problem relates to NSNull class. And here is my code to check object is null.

    NSString* text;
    if([text isKindOfClass:[NSNull class]])
    {
           //do something here if that object is null
    }

Hope this can help.

like image 21
Vu Hoang Son Avatar answered Sep 18 '22 03:09

Vu Hoang Son