I did search on how to check if NSDictionary key exists or not and came up with the solution. But still it throws me an error saying adding null value to the key. I am not sure if my code is correct or not. If anyone has any idea about this can help me.
NSDictionary *result;
id myImageURL = [result objectForKey:@"url"];
if ((NSNull *)myImageURL == [NSNull null])
myImageURL = @"";
id myImage = [result objectForKey:@"image"];
if ((NSNull *)myImage == [NSNull null])
myImage = @"";
Check if null add nothing and if not add the value. But it still gives me an error dont know why.
/****OUTPUT*****/
2011-08-11 14:56:06.668 Tab_Table_Win[6510:207] RESULTS : {
image = "<UIImage: 0xbc332c0>";
url = "http://a3.twimg.com/profile_images/999228511/normal.jpg";
}
2011-08-11 14:56:06.669 Tab_Table_Win[6510:207] url : http://a3.twimg.com/profile_images/999228511/normal.jpg
2011-08-11 14:56:06.670 Tab_Table_Win[6510:207] IMage : <UIImage: 0xbc332c0>
/*****Breaks Here ***/
2011-08-11 14:56:06.876 Tab_Table_Win[6510:207] RESULTS : {
}
2011-08-11 14:56:06.878 Tab_Table_Win[6510:207] url : (null)
2011-08-11 14:56:06.879 Tab_Table_Win[6510:207] IMage : (null)
2011-08-11 14:56:06.881 Tab_Table_Win[6510:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary setObject:forKey:]: attempt to insert nil key'
See if that works, rather than overthinking the NULL class.
Tommy explained this perfectly.
What I recommend is create an extension of the NSDictionary class like:
And the implementation file:
And instead of using
[dictionary objectForKey:@"keyName"];
in your code, useThis way, as Tommy explained, you'd be sending a method call to a nil which wouldn't crash the app but your object would get a nil value.
Hope this helps.
I got the same issue with JSONKit. The implementation there is
So this will definitely return NULL if the object isn't there. I check it like the following
the answer below worked for me:
https://stackoverflow.com/a/2784675/936957
Also note that you can get array of the keys in a dictionary using
Alright here's the actual answer which @Iomec almost had
That is the actual correct answer because, it comes as null and when you say myImage = [receivedObject...]; then if myImage = nil, you are in effect casting a null value(nil) into a class which is an exception, if not a running bug.
You should: 1) test for NSNull null value 2) if not nil then assign
If you code hasn't bugged out yet, it will in production when you have 8 apps running in the background one day.
Might want to add a bit more safety by checking to make sure it is NOT a string instead of just checking if it IS a nil. (To make sure it is not a number or anything else you might not want.)