【问题标题】:Stepping thru a plist to get at info通过 plist 获取信息
【发布时间】:2011-02-20 23:02:16
【问题描述】:

如果我有这样的 plist 设置

Key           Type         Value
Root          Array
 Item 0       Dictionary  
 -Title       String       Part One
 -Description String       Welcome to part one. Have fun
 Item 1       Dictionary  
 -Title       String       Part Two
 -Description String       Welcome to part two. Fun too.
 Item 2       Dictionary  
 -Title       String       Part Three
 -Description String       Welcome to part three. It's free
 Item 3       Dictionary  
 -Title       String       Part Four
 -Description String       It's part four. No more

如何逐步将所有标题放入一个数组中,将所有描述放入另一个数组中?

【问题讨论】:

    标签: iphone objective-c nsarray plist


    【解决方案1】:

    Collections Programming Topics for Cocoa

    NSArray *items = [[NSArray alloc] initWithContentsOfFile:@"items.plist"];
    NSMutableArray *titles = [[NSMutableArray alloc] init];
    NSMutableArray *descriptions = [[NSMutableArray alloc] init];
    
    for (NSDictionary *item in items) {
        [titles addObject:[item objectForKey:@"Title"]];
        [descriptions addObject:[item objectForKey:@"Description"]];
    }
    
    [items release];
    
    // Do something with titles and descriptions
    
    [titles release];
    [descriptions release];
    

    【讨论】:

      【解决方案2】:

      噢噢噢噢,这就是键值编码的魅力所在。

      NSArray * plistContents = [NSArray arrayWithContentsOfFile:pathToPlist];
      NSArray * titles = [plistContents valueForKey:@"Title"];
      NSArray * descriptions = [plistContents valueForKey:@"Description"];
      

      这里的秘密是,在数组上调用 valueForKey: 会返回一个新的对象数组,其中包含在数组中的每个事物上调用 valueForKey: 的结果。并且在字典上调用valueForKey: 可以等同于使用objectForKey:(如果您使用的键是键值对中的键)。如需更多信息,请参阅the documentation

      提醒一句:当您开始看到奇怪的结果时,使用“Description”键可能会导致您大吃一惊,因为一个拼写错误,您实际上会开始在每个字典上调用-description 方法(这不是你想要的)。

      【讨论】:

      • 戴夫·德隆摇滚!我离发帖还有几秒钟的路程。太棒了!
      猜你喜欢
      • 1970-01-01
      • 2021-08-25
      • 2015-06-11
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 2011-10-31
      相关资源
      最近更新 更多