9

I'm receiving some response from JSON, and is working fine, but I need to check for some null values,

I have found different answers but seems is not working still,

NSArray *productIdList = [packItemDictionary objectForKey:@"ProductIdList"];

I have tried with

if ( !productIdList.count )  //which breaks the app,

if ( productIdList == [NSNull null] )  // warning: comparison of distinct pointer types (NSArray and NSNull)

So what is happening? How to fix this and check for null in my array?

Thanks!

1
  • 1
    What do you mean “brakes the app”? If it's raising an exception, post the log messages. Commented Mar 1, 2012 at 6:05

4 Answers 4

35

Eliminate the warning using a cast:

if (productIdList == (id)[NSNull null])

If productIdList is in fact [NSNull null], then doing productIdList.count will raise an exception because NSNull does not understand the count message.

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

2 Comments

@MaKo ... and, implicitly, this works because [NSNull null] always returns the same object. == compares identity, not value.
I missed the cast to 'id' & was missing this check (ignored it due to compiler warning) for long time! thanks!
7

You can also check class of an object by using method isKindOfClass:.

For example, in your case you could do following:

if ([productIdList isKindOfClass:[NSArray class]])
{
     // value is valid
}

or (if you are sure that NSNull is indicating invalid value)

if([productIdList isKindOfClass:[NSNull class]])
{
     // value is invalid
}

2 Comments

There is only one singleton instance of NSNull so using == to check for it is shorter and more efficient.
But checking type of returned object is more safely.
5

You can use the isEqual selector:

if ( [productIdList isEqual:[NSNull null]] )

Comments

0

you should be clear what you want to check: the array is null which means the variable doesn't exist:


array == nil

Or the array has zero element which you can :


[array count] == 0

2 Comments

The NSDictionary class cannot store nil as a value, so JSON parsers (and property list parsers) use [NSNull null] instead to represent a null value, because there is a difference between a key being present with a null value, and a key being absent.
The first line says all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.