objectForKey 处的空数组导致 iPhone 应用程序崩溃
我有一个从 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;
}
该应用程序似乎崩溃了,因为并非所有照片都有注释,当它到达空数组时,它就会停止。我尝试了一些“if 语句”和其他一些技巧,但没有成功。我成功地使用此代码创建了图像数组,但显然“img”键的值不是带有字典的数组。任何帮助将不胜感激。提前致谢。
I have an array that gets created from JSON. The array looks like this:
[
{
"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
}
]
I pass the array to a function that enumerates thru the dictionary and creates a string then adds it to a comments array. My code looks like this:
-(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;
}
The app appears to crash because not all my photos have comments and when it gets to an empty array it comes to a halt. I've tried some "if statements" and a few other tricks to no avail. I used this code successfully to create an array of images, but obviously the value for the "img" key was NOT an array with a dictionary. Any help would be greatly appreciated. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,
[[comment objectForKey:@"photo_comments"] objectForKey:@"author"]
正在尝试在数组上使用 objectForKey,但这是行不通的。查看您的 json,photo_comments 是一个(可能为空)列表,包含对象。您还需要一个列表循环。(添加错误检查以适应。)
well,
[[comment objectForKey:@"photo_comments"] objectForKey:@"author"]
is trying to use objectForKey on an array, which won't work. Looking at your json, photo_comments is a (potentially empty) list, containing objects. You need one more list loop in there.(add error checking to suit.)