Why does this null check fail?

121 views Asked by At

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?

3

There are 3 answers

2
vadian On BEST ANSWER

(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) {
0
Miti On

You can also check for string is blank or not.

if(![imageUrl isEqualToString:@""])

Or

if(![imageUrl isKindOfClass:[NSNull class]])
0
Sambit Prakash On

nil represents nothing or in technical term, we can say that '\0' (according to C concepts). When ever we make an instance of any Class, by default Objective C makes it nil.

[NSNull null] will give an Object. In Objective C, use of NSNull is limited. It is used in collections (like NSArray and NSDictionary)

As you are using a NSDictionary, you can check it as below.

if ([dict objectForKey:@"imageUrl"] != [NSNull null]) {
    //your code...
}