iPhone JSON - 迭代NSArray并获取值

时间:2010-12-12 11:11:10

标签: iphone objective-c json nsarray

我一直在努力解决这个问题(昨晚我整个人都醒着把头撞在墙上)但希望有人可以帮助我。

我已经使用本教程连接到我的JSON数据源(http://www.mobileorchard.com/tutorial-json-over-http-on-the-iphone/)并且它工作正常但我现在想获取值(我认为通过对象键)。

我的json数据如下: [{ “ID”: “1”, “姓名”: “理查”, “NameOfFile”: “1.JPG”},{ “ID”: “395”, “姓名”: “亚历克斯”, “NameOfFile”: “390.jpg”}]

我用来连接它的代码如下。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    [connection release];

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];

    SBJSON *json = [[SBJSON new] autorelease];
    NSArray *myArray = [json objectWithString:responseString error:nil];
    [responseString release];   

    for (int i = 0; i < [myArray count]; i++)
    {
        for(int colIndex = 0; colIndex < 5; colIndex++) 
        {
            UIImage * myimage = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://www.goweruk.com/Images/Uploaded/220/873.jpg"]]];
            UIImageView *myimageview = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,50.0f, 50.0f)];
            [myimageview setImage:myimage];

            CGRect frameRect = myimageview.frame;
            frameRect.origin.x = (frameRect.size.width + 14) * colIndex;
            frameRect.origin.y = (frameRect.size.height + 14) * i;
            myimageview.frame = frameRect;

            [self.view addSubview:myimageview];
            [myimageview release];
        }
    }
}

所以我想做的就是在那个循环中,得到一个项目值。有谁知道我会怎么做?

1 个答案:

答案 0 :(得分:8)

NSArrayNSDictionary个对象的数组,因此您首先需要使用objectAtIndex:在所需索引处获取字典,然后使用{{1}遍历字典}:

for..in