2010-08-25 40 views
1

任何人都可以幫助正確加載字典對象到數組中。 將plist加載到字典對象中工作正常,我能夠將其中的一部分輸出到命令行中。 問題是,這種加載方式將每個名稱和價格集合放入數組中的同一個單元格中。 IE: 是否可以單獨加載它們?或者,也許在某種二維數組中有一個單元格用於名稱和其他價格。解析詞典從plist到數組

在此先感謝。

測試是一個可變數組。

NSString* path = [[NSBundle mainBundle] pathForResource:@"property" ofType:@"plist"]; 
NSDictionary* amountData = [NSDictionary dictionaryWithContentsOfFile:path]; 
if (amountData) { 
    Test = [NSMutableArray arrayWithArray: amountData]; 
} 

而我的plist結構爲:

<dict> 
<key>New item</key> 
<dict> 
    <key>Name</key> 
    <string>Property 1</string> 
    <key>Price</key> 
    <string>100000</string> 
</dict> 
<key>New item - 2</key> 
<dict> 
    <key>Name</key> 
    <string>Property 2</string> 
    <key>Price</key> 
    <string>300000</string> 
</dict> 
<key>New item - 3</key> 
<dict> 
    <key>Name</key> 
    <string>Property 3</string> 
    <key>Price</key> 
    <string>500000</string> 
</dict> 
<key>New item - 4</key> 
<dict> 
    <key>Name</key> 
    <string>Property 4</string> 
    <key>Price</key> 
    <string>600000</string> 
</dict> 
</dict> 

回答

1

你爲什麼不直接將其存儲爲一個數組?你的文件應該是這樣的:

<array> 
    <dict>...</dict> 
    <dict>...</dict> 
    <dict>...</dict> 
</array> 

而且你可以做這樣的事情:

NSArray *amountData = [NSArray arrayWithContentsOfFile: path]; 

否則這樣做會是這樣的正確方法:

Test = [NSMutableArray arrayWithArray: [amountData allValues]]; 
+0

問題的陣列的方法是,它返回每個行爲: 行0:{ 名稱= 「屬性1」; Price = 100000; } 我想知道如果更容易的方式加載這個,而不必手動解析括號等。 或者如果我可以直接從字典訪問值拉出讓我們說名稱。 – totallhellfail 2010-08-25 15:56:33

+0

我不確定我完全理解你的問題。你會得到的是你想要的陣列。獲取所有名稱可以使用像這樣的想法來完成:'[Test valueForKeyPath:@「name」]' - 返回一個包含所有名稱的數組。 – 2010-08-25 18:26:24

+0

這聽起來像我在找的東西; D謝謝。 – totallhellfail 2010-08-25 23:03:22

0

您正在致電

Test = [NSMutableArray arrayWithArray: amountData]; 

w hen amountData是一個NSDictionary,而不是一個數組......正如Max所建議的,你可以存儲一個數組plist而不是一個字典plist。

0
NSString* path = [[NSBundle mainBundle] pathForResource:@"property" ofType:@"plist"]; 
NSDictionary* amountData =  [NSDictionary dictionaryWithContentsOfFile:path]; 
if (amountData) { 
    Test = [NSMutableArray arrayWithArray: [amountData allValues]]; 
}