2

I have a NULL object returned from a JSON query string and I don't know how to check for it in an If statement. My syntax is below but I still don't seem to be able to trap for the NULL class (i.e., if nothing is returned then no text variable can be set therefore it MUST be a NULL class?), anyway, I need to check that the @"BillingStreet" has something in it and if not to avoid processing it (else the app crashes as it tries to set nothing to the text value of one of the fields in the VC):

- (void) tableView: (UITableView *)itemTableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath{
    NSDictionary *obj = [self.dataCustomerDetailRows objectAtIndex:indexPath.row];
    NSString *text = [obj objectForKey:@"BillingStreet"] == nil ? @"0" : [obj objectForKey:@"BillingStreet"];
    NSLog(@"%@",text);
    if (text.class == NULL){
    } else {
        NSLog(@"no street");
        self.labelCustomerAddress.text = [obj objectForKey:@"BillingStreet"];
    }
}

2 Answers 2

8

A JSON "null" value is converted to [NSNull null], which you can check for with

if (text == [NSNull null]) ...

because it is a singleton.

Alternatively, you can check if the object contains the expected type, i.e. a string:

NSString *text = [obj objectForKey:@"BillingStreet"];
if ([text isKindOfClass:[NSString class]]) {
    self.labelCustomerAddress.text = text;
} else {
    self.labelCustomerAddress.text = @"no street";
}

This is more robust in the case that a server sends bad data, e.g. a number or an array instead of a string.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Martin, tested and that works (I put this in: ' if (text == (id)[NSNull null] || text.length ==0 || [text isEqualToString:@"null"])' I can across the answeer as well in this question, so I may have duplicated my question: stackoverflow.com/questions/8785124/exception-if-nil-or-null
I think this is more efficient as it removes the need for creating a string variable : 'if ([obj objectForKey:@"BillingStreet"] == (id)[NSNull null])'
@Bartley: No, assigning text = [obj objectForKey:@"BillingStreet"] is more efficient because it retrives the dictionary value only once.
6

text == nil ? @"0" : text

or

text ? text : @"0"

But if you get it from JSON then you may get instance of NSNull class. In this case you should check

text && ![text isKindOfClass:[NSNull class]] ? text : @"0"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.