how to check NSDictionary key value is null?

2.5k Views Asked by At

how i can check NSDictionary key value is null ?

i am using ASIHttpRequest:

NSDictionary *tempDict=[[[request responseString] JSONValue] valueForKey:@"data"];

if key value is "0 key/value pair" and crease please give me a answer.

thank you.

3

There are 3 best solutions below

0
On BEST ANSWER

You should check NSDictionary key values before access it. Put a condition with same key if it contains any not null value than proceed else take a precaution.

if([[[request responseString] JSONValue] valueForKey:@"data"]])
   {
     NSDictionary *tempDict=[[[request responseString] JSONValue]valueForKey:@"data"];
   }
else
{
   // Show alert here 

}
0
On

you can check if the key is exists inside NSDictionary like this:

NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"Ron",@"first_name",@"25",@"age", nil];

if([self dictionary:dict containsKey:@"age"])
{
    // Key exists
}
else
{
    // Key does not exists
}

Use this helper function :

-(BOOL)dictionary:(NSDictionary *)dictionary containsKey:(id)key
{
    if(dictionary != nil)
    {
        if([dictionary objectForKey:key])
        {
            return YES;
        }
    }

    return NO;
}
0
On

Do you just want to check if NSDictionary is null or not? Then you can simply check like this.

if (tempDict==nil)
     {
    Nslog(@"Dictonary is null");
    }
    else
    {
    }