Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement for dictionary objectforkey:@"key" when value is <null>

Tags:

objective-c

I am working with objective c for an iphone app.

I see that [dictionary objectForKey:@"key"] return <null>. Doing a if([dictionary objectForKey:@"key"] == nil || [dictionary objectForKey:@"key"] == null) does not seem to catch this case.

Doing a if([[dictionary objectForKey:@"key"] isEqualToString:@"<null>"]) causes my program to crash.

What is the correct expression to catch <null>?

More Details An if statement for nil still isn't catching the case... Maybe i'm just too tired to see something, but here's additional info:

Dictionary is populated via a url that contains json data like so:

NSURL *url = [NSURL URLWithString:"http://site.com/"];

dataresult = [NSData dataWithContentsOfURL:url];

NSError *error;
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:dataresult options:kNilOptions error:&    error];

doing an NSLog on the dictionary gives this output:

{
    key = "<null>";
    responseMessage = "The email / registration code combination is incorrect";
}
like image 436
John Avatar asked Jun 03 '12 22:06

John


2 Answers

You have an instance of NSNull. Actually, the instance, since it's a singleton.

Cocoa collections can't contain nil, although they may return nil if you try to access something which isn't present.

However, sometimes it's valuable for a program to store a thing meaning "nothing" in a collection. That's what NSNull is for.

As it happens, JSON can represent null objects. So, when converting JSON to a Cocoa collection, those null objects get translated into the NSNull object.

When Cocoa formats a string with a "%@" specifier, a nil value will get formatted as "(null)" with parentheses. An NSNull value will get formatted as "<null>" with angle brackets.

like image 169
Ken Thomases Avatar answered Sep 17 '22 20:09

Ken Thomases


New answer:

Thanks for adding the detail. It looks like the "dataresult" you are setting is not a JSON object so no wonder you're getting wacky results from putting a raw string into "[NSJSONSerialization JSONObjectWithData:]. You may need to do some basic error checking on your data before you call anything JSON related.

Original answer:

First off, if this were my code, I wouldn't name a "NSDictionary" object "array" (and I see you caught my comment in your edit... hope you get some sleep soon!).

Secondly, what you are looking for is "nil", not a string named "<null>". As Apple's documentation for objectForKey: states, if an object is not found for the key you are asking for, a nil is returned. The Xcode console tries to be helpful in converting nil objects to "<null>" strings in it's output.

Do "if [dictionary objectForKey: @"key"] != nil" and you should be happier.

like image 22
Michael Dautermann Avatar answered Sep 20 '22 20:09

Michael Dautermann