manuelBetancurt
manuelBetancurt

Reputation: 16128

ios check if nsarray == null

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!

Upvotes: 9

Views: 11123

Answers (4)

Devang
Devang

Reputation: 1541

You can use the isEqual selector:

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

Upvotes: 5

Nekto
Nekto

Reputation: 17877

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
}

Upvotes: 7

scorpiozj
scorpiozj

Reputation: 2687

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

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385540

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.

Upvotes: 35

Related Questions