2010-12-12 93 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