Search This Blog

Saturday, July 17, 2010

NSDictionary stringForKey: and Casting [NSNull null] to NSString*

Programmer Question

I was recently told casting [NSNull null] to (NSString*) was "terrible".



However, -[NSDictionary stringForKey:] method will return [NSNull null] if the key is not in the dictionary, and if I don't do the cast the compiler yells at me.



Am I missing something?



EDIT:



My mistake... and I think I might be beginning to see the problem...



As everyone has pointed out, there is no stringForKey: method on NSDictionary, and yes, I was thinking about the user defaults when I asked the question... so I went back and looked at what I was doing... here it is:



NSString * someValue = (NSString*)[myDictionary objectForKey:@"key"];
if (someValue == (NSString*)[NSNull null]) ...


if I don't do the cast in this case, I get the following error:



warning: comparison of distinct Objective-C types 'struct NSNull *' and 'struct NSString *' lacks a cast


Casting the value "solves" the problem, and I'd rather not write 10 lines where one will do...



Is this bad? Where will I run into problems?



ALSO:



This dictionaries are coming from a JSON library... and NULLs are valid values in this case.



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails