IOS cannot check if object is null

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 a UITextField , what am I doing wrong? I try to display some text only when the user enters something into the field.

Best wishes,

+6
source share
6 answers

Solution found! ![txtName.text isEqualToString:@""]

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

The text in the text field is the value of the NSString instance or nil ; it is never equal to an instance of the NSNull class (which does not match nil ). Since the first comparison is always true, then the entire if-condition evaluates to true and a message appears.

You can fix the if condition for

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

or, since sending a message of length in nil will return 0, it’s still easy

 if (txtName.text.length != 0 ) 

although I usually use the 1st option with 2 comparisons

+11
source

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

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

txtName.text never nil (you can just compare with nil for a null check, by the way) - the text field always contains some text, even if it is empty. Thus, the first clause is always true, and the field will always be displayed.

+6
source

I have the same problem as you. This problem belongs to the NSNull class. And so my code for checking the object is null.

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

Hope this helps.

+3
source
 #define SAFESTRING(str) ISVALIDSTRING(str) ? str : @"" #define ISVALIDSTRING(str) (str != nil && [str isKindOfClass:[NSNull class]] == NO) #define VALIDSTRING_PREDICATE [NSPredicate predicateWithBlock:^(id evaluatedObject, NSDictionary *bindings) {return (BOOL)ISVALIDSTRING(evaluatedObject);}] SAFESTRING(PASS_OBJECT OR STRING); 
+1
source

Please try the following:

when the value of myObj is nil or zero>

 if([myObj isEqual:[NSNull class]] || !myObj) { // your code } 
0
source

Source: https://habr.com/ru/post/902501/


All Articles