Search code examples
objective-cnsnull

Why does this null check fail?


I am using this simple code to check if an NSString object is null, but for some reason it fails

here is my simple check

NSString *imageUrl = [dict objectForKey:@"imageUrl"];

    NSLog(@"Jonge: %@", imageUrl);

    if(![imageUrl isEqual:[NSNull null]]) {
        NSLog(@"In the loop");
        NSURL *url = [[NSURL alloc]initWithString:imageUrl];
        NSData *data =[NSData dataWithContentsOfURL:url];
        cell.imageView.image = [UIImage imageWithData:data];
    }

The debug clearly shows the object is null as follows

2017-10-23 11:48:22.711228+0800 NWMobileTill[46614:7498779] Jonge: (null)

But I still end up in the loop as below

2017-10-23 11:48:22.711367+0800 NWMobileTill[46614:7498779] In the loop

Why is my null check not working?


Solution

  • (null) represents nil, not [NSNull null], so the check imageUrl != NSNull succeeds.

    You have to write

    if (imageUrl) {
    

    which is the same as

    if (imageUrl != nil) {