2009-06-04 75 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>