0

I am currently doing something like this

NSDictionary *imageDataDictionary = nil;
imageDataDictionary = (NSDictionary *)metadataItem.value;
if(imageDataDictionary != nil)
{
    if ([imageDataDictionary objectForKey:@"data"] != nil) <---Crashes
    {
    }
}

The app crashes on

if ([imageDataDictionary objectForKey:@"data"] != nil)

because it has 0 key value pairs. I wanted to know what would the right way be to check if a NSDictionary is valid and if it has any key value pairs

This is the messages

2015-04-19 15:56:37.255 MBlast[61278:2115186] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x7c16a7e0'
Rajeshwar
  • 11,179
  • 26
  • 86
  • 158
  • It doesn't crash in that case https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html#//apple_ref/occ/instm/NSDictionary/objectForKey: Also, you don't need to check imageDataDictionary for nil, it will work without it – creker Apr 19 '15 at 22:39
  • 2
    What does the crash say? – NobodyNada Apr 19 '15 at 22:41
  • My bet is that `metadataItem.value` is not a dictionary. – Kevin Apr 19 '15 at 22:52
  • Don't attempt to do `objectForKey` on an NSData object. It's never going to work. – Hot Licks Apr 19 '15 at 23:48

1 Answers1

2

You are casting an object of unspecified type to an NSDictionary. That tell the compiler "trust me, this is a dictionary."

If the object is NOT a dictionary, you'll crash. That is almost certainly what's going on here. Add some error checking:

if (![mediadataItem.value isKindOfClass: [NSDictionary class]])
  return; //The object isn't a dictionary. Bail.
NSDictionary *imageDataDictionary;
imageDataDictionary = (NSDictionary *)metadataItem.value;
if(imageDataDictionary != nil)
{
    if ([imageDataDictionary objectForKey:@"data"] != nil) <---Crashes
    {
    }
}
Duncan C
  • 128,072
  • 22
  • 173
  • 272