I have a simple NSDictionary that I am trying to populate with data from an external site via JSON that is returned. The JSON that is returned is fine but I am haveing trouble getting actual data for a specific key.
Here is the JSON data printed to the console.
This is my JSON data:
(
{
CategoryID = 12345;
CategoryName = "Baked Goods";
},
{
CategoryID = 12346;
CategoryName = Beverages;
},
{
CategoryID = 12347;
CategoryName = "Dried Goods";
},
{
CategoryID = 12348;
CategoryName = "Frozen Fruit & Vegetables";
},
{
CategoryID = 12349;
CategoryName = Fruit;
},
{
CategoryID = 12340;
CategoryName = "Purees & Soups";
},
{
CategoryID = 12341;
CategoryName = Salad;
},
{
CategoryID = 12342;
CategoryName = "Snack Items";
},
{
CategoryID = 12343;
CategoryName = Vegetables;
}
)
The error I am getting is:
Terminating app due to uncaught exception
‘NSInvalidArgumentException’, reason: ‘-[__NSCFArray
enumerateKeysAndObjectsUsingBlock:]: unrecognized selector sent to
instance 0x6884000’
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSError *error = nil;
// Get the JSON data from the website
NSDictionary *categories = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (categories.count > 0){
NSLog(@"This is my JSON data %@", categories);
[categories enumerateKeysAndObjectsUsingBlock: ^(__strong id key, __strong id obj, BOOL *stop) {
NSLog(@"Key = %@, Object For Key = %@", key, obj); }];
}
I’m not sure why this is happening but I’m sure it’s something simple like I am using the incorrect object or something.
Help is appreciated.
+JSONObjectWithData:options:error:is returning an NSArray not an NSDictionary.'-[__NSCFArray enumerateKeysAndObjectsUsingBlock:]is the key part of the error message. It tells you that you are calling-enumerateKeysAndObjectsUsingBlock:on an array.For this case, you could use
-enumerateObjectsUsingBlock:instead.If you are not sure wether a NSArray or an NSDictionary will be returned, you can use
-isKindOf:From enumerateObjectsUsingBlock:
So it should be called as such
A quick read of the documentation really can save you lots of frustration.