Z. Zepos Z. Zepos - 4 months ago 14
JSON Question

objectForKey throws an exception on count if it contains a single value

I have a dictionary JSON dictionary like

{
county = "XXXXX";
states = (
"YYYYY",
"ZZZZZ"
);
}


After reading the JSON dictionary the data is in an array. I then want to create a different array with the data and I am using the following code

for (NSString *key in array) {
NSMutableArray *myData =[[NSMutableArray aalloc] init];
myData = [array objectForKey:key];
int count = [myData count];
}


When key is 'states', it works fine. If key is 'country', then it throws an exception on count because objectForKey returns a NSString. How to resolve this? How to find how many objects the objectForKey will return?

Answer

Check out this answer from @HDdeveloper:

if([object isKindOfClass:[NSString class]] == YES)
{
     NSLog(@"String rx from server");
}
else if ([object isKindOfClass:[NSDictionary class]] == YES)
{
     NSLog(@"Dictionary rx from server");
}
else if ([object isKindOfClass:[NSArray class]] == YES)
{
     NSLog(@"Array rx from server");
}

Basically, after you get the objectForKey, then you need to check what kind of object that is and use it accordingly.