0

What can I do to avoid the app crashing when it encounters a null value?

the error message I get is:

-[NSNull isEqualToString:]: unrecognized selector sent to instance.

I tried this conditional statement to check for a null value, but it still crashes. listingWebAddress is a NSString.

 if (listingWebAddress == nil)
    {
        [webLabel setText:@""];

    } else {

    [webLabel setText:listingWebAddress];

    }

it works fine when a "listingWebAddress" exists.

thanks for the help :)

Update:

thanks to The Tiger's response the code now works. The solution was:

 if (![listingWebAddress isKindOfClass:[NSNull class]])
    {
        // do your task here

        [webLabel setText:listingWebAddress];

    } else {

        [webLabel setText:@"no web url"];

    }
hanumanDev
  • 6,592
  • 11
  • 82
  • 146
  • @Kerni How about answering the question instead of spamming?! NSNull is quite a common issue, especially when it comes to JSONs returned from APIs. – thedp May 28 '15 at 18:44

3 Answers3

1

1. If it is NSString you can check its length and if it is an NSArray you check its count.

2. You can simply put it in if condition, condition will return YES only in case of the object is not nil. Example:

if (object)
{
    //do your task here
}

3. In Objective-C You can check it by its class.

if (![object isKindOfClass:[NSNull class]])
{
   // do your task here
}

The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values).

TheTiger
  • 13,264
  • 3
  • 57
  • 82
  • thanks! it is an NSString. I updated my code above and got rid of the mutableCopy. I then tried if (listingWebAddress) { [webLabel setText:listingWebAddress]; } but it still crashes with -[NSNull isEqualToString:]: unrecognized selector sent to instance – hanumanDev Aug 09 '13 at 10:28
  • Of course you are calling `isEqualToString:` method by an `NSNull` object while it is use for an `NSString` object. Have you checked its class by `[listingWebAddress :isKindOfClass:[NSNull class]]` ? – TheTiger Aug 09 '13 at 10:31
  • that worked! thanks so much! it was getting annoying :D if (![listingWebAddress isKindOfClass:[NSNull class]]) { // do your task here [webLabel setText:listingWebAddress]; } else { [webLabel setText:@"no web url"]; } – hanumanDev Aug 09 '13 at 10:33
0

It looks like listingWebAddress is already NSNull, which doesn't support method mutableCopy. I would change condition to:

if ( [listingWebAddress isKindOfClass: [NSNull class]] == NO){
  ... rest of logic 
}
The Tosters
  • 417
  • 3
  • 15
0

try this

if(listingWebAddress !=[NSNull null]
{
   //your code
}
Aman Aggarwal
  • 3,754
  • 1
  • 19
  • 26