2010-12-12 65 views
1

我一直试图自己解决这个问题(我昨晚醒来时把头撞在墙上)但希望这里有人能帮助我。iPhone JSON - 迭代NSArray并获取值

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

我的json数据如下: [{“Id”:“1”,“Name”:“Richard”,“NameOfFile”:“1.jpg”},{“Id”:“395”, “Name”:“Alex”,“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]; 
     } 
    } 
} 

所以我想要做的是在该循环内获取一个项目值。有谁知道我会怎么做?

回答

8

NSArrayNSDictionary对象的数组,所以你首先需要获得的字典,使用objectAtIndex:所需的索引,然后通过使用for..in字典遍历:

for (int i = 0; i < [myArray count]; i++) 
{ 
    NSDictionary *dict = [myArray objectAtIndex:i]; 
    for(NSString *key in dict) { 
     //do something with key or [dict objectForKey:key]; 
    } 
} 
+0

这就是我一直在寻找。我虽然修改它 - 我用 NSDictionary * dict = [myArray objectAtIndex:i]; NSLog([dict objectForKey:@“NameOfFile”]); – tmutton 2010-12-12 11:36:58