objectForKey的空数组崩溃iPhone应用程序

时间:2011-04-18 02:06:43

标签: iphone objective-c json

我有一个从JSON创建的数组。该数组如下所示:

[
    {
        "img": "images/photo_10.jpg", 
        "title": "None", 
        "photo_comments": [
            {
                "body": "my comment", 
                "author": "john", 
                "created": "2011-04-17 14:21:11"
            }
        ], 
        "id": 24
    }, 
    {
        "img": "images/photo_8.jpg", 
        "title": "None", 
        "photo_comments": [], 
        "id": 22
    }


]

我将数组传递给一个函数,该函数通过字典枚举并创建一个字符串,然后将其添加到一个注释数组中。我的代码如下所示:

    -(NSArray *)formatCommentArray:(NSArray *)array  
{

    NSMutableArray *comments = [[[NSMutableArray alloc] init] autorelease];

    for (NSDictionary *photo in array)
    {   


           for( NSDictionary *comment in [photo objectForKey:@"photo_comments"])
           {

               NSString *commentString = [NSString stringWithFormat:@"%@: %@", 
                                           [comment objectForKey:@"author"], [comment objectForKey:@"body"]];



               [comments addObject:commentString];


           }




    return comments;

}

应用程序似乎崩溃了,因为并非我的所有照片都有评论,当它到达一个空数组时就会停止。我尝试了一些“如果声明”和一些其他技巧无济于事。我成功使用此代码创建了一个图像数组,但显然“img”键的值不是带字典的数组。任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:1)

好吧,[[comment objectForKey:@"photo_comments"] objectForKey:@"author"]正在尝试在数组上使用objectForKey,这将无法正常工作。看着你的json,photo_comments是一个(可能是空的)列表,包含对象。你需要一个更多的列表循环。

for (NSDictionary *photo in array)
{
  // do stuff with photo.img, photo.title etc

  for (NSDictionary *comment in [photo objectForKey:@"photo_comments"])
  {
    // do stuff with comment.author, comment.body etc
  }
}

(添加错误检查以适应。)