2012-02-23 71 views
0

我想知道如何從字典中檢索數組,然後從數組對象中檢索字典。如何從字典中檢索數組,然後檢索該數組中的字典?

我正在追蹤這個http://ios.biomsoft.com/2011/09/11/simple-xml-to-nsdictionary-converter/

itemDict 
(
     { 
     postID =   { 
      text = 26; 
     }; 
     score =   { 
      text = 20; 
     }; 
     title =   { 
      text = "http://www.google.com quiz"; 
     }; 
     url =   { 
      text = "http://www.google.com"; 
     }; 
    }, 
     { 
     postID =   { 
      text = 27; 
     }; 
     score =   { 
      text = 10; 
     }; 
     title =   { 
      text = "http://www.google.com"; 
     }; 
     url =   { 
      text = "http://www.google.com"; 
     }; 
    }, 
     { 
     postID =   { 
      text = 3; 
     }; 
     score =   { 
      text = 41; 
     }; 
     title =   { 
      text = "http://www.google.com"; 
     }; 
     url =   { 
      text = "http://www.google.com"; 
     }; 
    }, 
     { 
     postID =   { 
      text = 35; 
     }; 
     score =   { 
      text = 10; 
     }; 
     title =   { 
      text = "Sample Video"; 
     }; 
     url =   { 
      text = "http://www.google.com"; 
     }; 
    }, 
     { 
     postID =   { 
      text = 43; 
     }; 
     score =   { 
      text = 30; 
     }; 
     title =   { 
      text = "sample"; 
     }; 
     url =   { 
      text = "http://www.google.com"; 
     }; 
    } 
) 

回答

1

好吧,你想要做的是以下幾點。

從我可以從發佈的鏈接中搜集的內容,您可以獲得頂級NSDictionary,然後在其中包含XML。 NSDictionary內部會有一個對象,從你的例子來看,它可能是itemDict,但在我看來,它更像是一個NSArray。

從這裏,我會將NSArray存儲在另一個裏面。

該數組內的每個對象都是與其匹配的鍵和對象的NSDictionary。顯然我在談論這一點。

{ 
    postID =   { 
     text = 26; 
    }; 
    score =   { 
     text = 20; 
    }; 
    title =   { 
     text = "http://www.google.com quiz"; 
    }; 
    url =   { 
     text = "http://www.google.com"; 
    }; 
}, 

也許像下面的東西可以讓你深入下潛。

NSArray *itemArray = [xmlDictionary objectForKey:@"itemDict"]; 

for (NSDictionary *dict in itemArray) { 

    NSLog(@"Dictionary: %@", dict); 

} 

該代碼應該顯示NSArray內的每個NSDictionary的輸出。從這裏,它是一個簡單的情況下做任何你想要的NSDictionary。

編輯

剛把再看看我想我會在添加這一點。 看來每個NSDictionary我們會與上面的代碼,然後有一個關鍵的另一個對象,該對象存儲在另一個字典內。如果你問我這個XML,真的很奇怪...

但是,解決方法可能如下。

NSArray *itemArray = [xmlDictionary objectForKey:@"itemDict"]; 

for (NSDictionary *dict in itemArray) { 

    NSLog(@"Dictionary: %@", dict); 

    for (NSDictionary *dictObject in [dict allKeys]) { 

     NSLog(@"Dictionary Object: %@", dictObject); 

    } 

} 

如果這不是你想要做的,請編輯你的問題,這樣我可以糾正我的反應。

希望有幫助!

1

讓我們假設你分析它,並有這樣的事情:

(
//object 0 
    { 
    postID= 26; 
    score = 20; 
    title = www.google.com 
    url = www.google.com 
    }, 
//object 1 
    { 
    postID= 27; 
    score = 10; 
    title = www.google.com 
    url = www.google.com 
    }... 
    ) 

這是你的陣列。

的objectAtIndex:0在此示例中是:

{ 
postID= 26; 
score = 20; 
title = www.google.com 
url = www.google.com 
} 

是一個字典。