We have the following method where we are trying to access an array object at a given index. The array is resultArr. When we do a resultArr count it gives us a result of 13. So we know that the array is not null but when we try to do objectAtIndex it crashes with the error.
Function:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray *keys = [json allKeys];
NSLog(@"keys: %@",keys);
NSArray* htmlAttributions = [json objectForKey:@"html_attributions"]; //2
NSArray* resultArr = (NSArray *)[json objectForKey:@"result"]; //2
NSArray* statusArr = [json objectForKey:@"status"]; //2
NSLog(@"htmlAttributions: %@",htmlAttributions);
NSLog(@"result: %@", resultArr); //3
NSLog(@"status: %@", statusArr); //3
NSLog(@"resultCount: %d",[resultArr count]);
[resultArr objectAtIndex:0];
}
Error:
2012-04-01 22:31:52.757 jsonParsing[5020:f803] resultCount: 13 2012-04-01 22:31:52.759 jsonParsing[5020:f803] -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6d2f900 2012-04-01 22:31:52.760 jsonParsing[5020:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6d2f900'
*** First throw call stack:
Thank you.
The error message is fairly descriptive. One of the objects that your code expects to be an
NSArrayis actually anNSDictionary. You cannot access fields inside of anNSDictionaryby usingNSArraymethods (and casting fromNSDictionary*toNSArray*will not convert anNSDictionaryinto anNSArray).This would mean that inside of the JSON, one of your elements was serialized as an object/associative array instead of as a plain array. You can easily determine which one by looking at your JSON data as text, and finding the item that uses
{and}instead of[and].