【问题标题】:Convert dictionary items from plist to NSArray将字典项从 plist 转换为 NSArray
【发布时间】:2011-10-14 05:03:39
【问题描述】:

我有一个具有以下架构/结构的 plist:

dictionary
   key1
    item1
   key2
    item2
   key3
    item3
dictionary
   ...

并且我想将每个字典的第一个键 (key1) 的项目 (item1) 加载到 NSArray,以便我可以将 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"];

但这不作为命令存在。看来我需要一些帮助... :)

【问题讨论】:

    标签: objective-c ios dictionary nsarray plist


    【解决方案1】:

    您可以循环遍历数组并以这种方式添加对象:

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

    【讨论】:

      【解决方案2】:

      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。

      我认为这就是您所需要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-31
        • 2011-09-19
        • 2010-09-20
        • 1970-01-01
        • 1970-01-01
        • 2012-11-03
        • 2019-02-06
        相关资源
        最近更新 更多