2009-06-04 122 views
1

訪問元素我想使用字典的plist的,如下圖所示: alt text http://i42.tinypic.com/14uwffa.jpg從字典的plist

我讀入一個臨時的字典就好了。

我想知道的是,如果有一個簡單的方法來獲取字符串的孩子(實際上是一個數組中的單個元素,你可以看到)。

我最初嘗試過objectAtIndex,但那當然是返回一個數組,而不是字符串值。我接下來嘗試使用一個NSEnumerator(一個objectEnumerator),然後使用objectAtIndex:0來讓我的字符串工作。

但我真的希望有一個更簡單的方法來做到這一點。

編輯:澄清我正在嘗試做什麼。

我想使用鍵值(例如「所有項目」)填充tableview cell.text,然後使用字符串值(例如「find.png」),以幫助通過UIImage填充cell.image imageNamed :。我寧願不使用硬編碼的值(比如objectForKey:@「All Items」),這樣我就可以更改plist中的數據,而不用更改代碼。

+0

你到底想幹什麼?這些數組中是否會有多個感興趣的項目? – 2009-06-04 02:25:14

回答

2

您需要在字典上調用objectForKey:才能獲得其中一個數組,然後在數組上調用objectAtIndex:0(或只是lastObject)以獲取字符串。您可以在這兩種方法調用組合成一行代碼,例如:

[[dictionary objectForKey:@"All Items"] lastObject]; 
+0

我想他想要他們所有......這和他所做的一樣,除了使用lastObject而不是objectAtIndex:0。 – 2009-06-04 02:24:32

0

您可以使用字典的快速列舉:

for (id key in dict) { 
    NSArray *array = [dict objectForKey:key]; 
    NSLog(@"key: %@, value: %@", key, [array objectAtIndex:0]); 
} 
0
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    // get documents path 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    // get the path to our Data/plist file 
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"DecisionName.plist"]; 
    NSLog(@"Error in dictionary"); 
    NSLog(@"HELLO"); 
    NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; 

    NSArray *testChoice = [[NSArray alloc] initWithArray:[plistDict objectForKey:selectedDecision]]; 
    self.choices = [testChoice objectAtIndex:0]; 
    self.preferences = [testChoice objectAtIndex:1]; 


This code will be helpful which use to get values from plist having following structure...... 

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<array> 
    <array> 
     <string>Toyota</string> 
     <string>Honda</string> 
    </array> 
    <array> 
     <string>Speed</string> 
     <string>Reliability</string> 
     <string>Price</string> 
    </array> 
</array> 
</plist>