2011-07-27 115 views
1

我有一个具有以下结构/构造的plist中:转换从plist中字典项的NSArray

dictionary 
    key1 
    item1 
    key2 
    item2 
    key3 
    item3 
dictionary 
    ... 

,我想为每一个字典的第一密钥(KEY1)到一个NSArray加载项(ITEM1) ,这样我可以将nsarray加载到UITableView中。

我凸轮这一点:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; 

    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path]; 

,然后我想补充是这样的:

tablearray = [array objectsForKey:@"key1"]; 

,但不存在的命令。好像我需要一些帮助... :)

回答

2

你也可以遍历数组,并添加Objekts这样:

NSMutableArray *tablearray = [NSMutableArray arrayWithCapacity:[array count]]; 
for (NSDictionary *dict in array) { 
    [tablearray addObject:[dict objectForKey:@"key1"]]; 
} 
+0

正常工作,它的这么简单:)谢谢! – JonasG

0

Apple提供了pList programming guide,它描述了如何从pList读取并写入它。你可以通过它。

我们将从plist中作为NSData的获取数据,并将其转换成的NSDictionary,通过以下方法,

NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; 

NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization 
      propertyListFromData:plistXML 
      mutabilityOption:NSPropertyListMutableContainersAndLeaves 
      format:&format 
      errorDescription:&errorDesc]; 

可以使用

NSMutableArray * myArray = [NSMutableArray alloc] init]; 

//temp is the response dictionary 
NSArray * myKeys = [temp allKeys]; 
for (int index = 0; index<[myKeys count]; index++) { 


id value = [temp valueForKey:[myKeys objectAtIndex:index]]; 
[myArray addObject:value]; 

} 
添加应答词典介绍数组

现在使用myArray。

我认为这是你需要的。