开发者

NSDictionary error. How to solve it?

I use touchjson library. I receive json structure开发者_如何转开发.

  1. {"My dishes": ""} if i have not my dishes or
  2. {"My dishes": [{"dish": "rice with fish""restaurant_id": "35", "latitude": "39.783871","longitude": "-96.314759"}]} if i have a dish.

-

NSDictionary *all_dish = [dictionary objectForKey:@"My dishes"];
for (NSDictionary *my_dish in all_dish) {
  //some code
}

in the first case , i get

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x2900688'

How to solve the problem?


In the first case the object for key My dishes is not a dictionary, but a NSString, which does not support fast enumeration.

In the second case, all_dishes isn't a NSDictionary but a NSArray. I am surprised it works.

The way no dishes is handled is broken from where I stand: if you have no dishes My dishes should have a value of null or an empty list, not "".

If you can't control this, check whether the value of My dishes is an NSArray before attempting to enumerate over it.


if ([allDish isKindOfClass: [NSDictionary class]]) {
    for (NSDictionary *my_dish in all_dish) {
        if ([myDish isKindOfClass: [NSDictionary class]]) {
            //...
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜