0

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?

Balasubramanian
  • 5,274
  • 6
  • 33
  • 62
Matt Douhan
  • 2,053
  • 1
  • 21
  • 40
  • Possible duplicate of [What's the difference between \[NSNull null\] and nil?](https://stackoverflow.com/questions/836601/whats-the-difference-between-nsnull-null-and-nil) – Balasubramanian Oct 23 '17 at 06:16
  • Closely related: [What's the difference between (null) vs ?](https://stackoverflow.com/q/11287590) – jscs Oct 23 '17 at 12:35

3 Answers3

0

(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) {
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Is there a document about the different types null nil etc? I googled but could not find a good one – Matt Douhan Oct 23 '17 at 04:23
  • 2
    `NSNull` is used only in a few cases. Mattt Thompson wrote an [article about `nil / Nil / NULL / NSNull`](http://nshipster.com/nil/) – vadian Oct 23 '17 at 04:27
0

You can also check for string is blank or not.

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

Or

if(![imageUrl isKindOfClass:[NSNull class]])
Miti
  • 119
  • 1
  • 7
0

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...
}
Sambit Prakash
  • 341
  • 4
  • 15