Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if NSDictionary key is NULL

I'm trying to check if an object exist for the key next_max_id in my JSON response dictionary. I've tried the following ways to check:

  • if ([[pagination objectForKey:@"next_max_id"] isKindOfClass:[NSNull class]]) ...
  • if ([pagination objectForKey:@"next_max_id"] == [NSNull class]) ...
  • if ([pagination objectForKey:@"next_max_id"]) ...

However, when the pagination dictionary is empty i.e. (pagination = {};), I get these error messages:

-[NSNull objectForKey:]: unrecognized selector sent to instance ...
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull objectForKey:]: unrecognized selector sent to instance ...

How else can I check for if the object or rather the key exist, without a crash?

Updated: When the key next_max_id exist inside pagination, the JSON response would be like this

"pagination": {
    "next_url": "https://api.instagram.com/v1/tags/puppy/media/recent?access_token=fb2e77d.47a0479900504cb3ab4a1f626d174d2d&max_id=13872296",
    "next_max_id": "13872296"
}
like image 566
Scott Avatar asked Dec 15 '22 19:12

Scott


2 Answers

if( [pagination objectForKey:@"your_key"] == nil ||  
    [[pagination objectForKey:@"your_key"] isEqual:[NSNull null]] ){
    //nil dictionary
}
like image 117
Vijay Yadav Avatar answered Dec 29 '22 21:12

Vijay Yadav


With the error that you describe, pagination is not an NSDictionary, but pagination itself is an NSNull object. So the first check before everything else would be

if (pagination == [NSNull null]) ...

That wouldn't happen if your JSON data contains "pagination": {} but it would happen if your JSON data contains "pagination": null .

like image 22
gnasher729 Avatar answered Dec 29 '22 19:12

gnasher729