在Cocoa中读取plist文件

时间:2011-10-03 05:19:34

标签: cocoa plist

我有一个看起来如下的plist。什么是读取plist的首选方法,如何将其读入数组?我可以创建NSMutableDictionary,加载此plist的内容,将密钥加载到Array中,然后使用for循环读取前2个键 - SomeDataMoreData。但我无法解析所有其他键(Key1Key2Key3)。我该怎么做呢?下面的粘贴代码通过前2个键。 (SomeDataMoreData)。感谢。

plist中:

<?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">
<dict>
    <key>SomeData</key>
    <array>
        <dict>
             <key>Key1</key>
             <false/>
             <key>Key2</key>
             <dict>
                       <key>Key3</key>
                       <integer>0</integer>
                  </dict>
            </dict>
       </array>
       <key> MoreData</key>
   </dict>  
  </plist>       

代码:

-(IBAction)modifyPlist:(id)sender{

    NSLog(@"Listing Keys");
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/Users/sureshb/Documents/myprogs/plistMod/com.test.plist"];

    NSArray *keys = [dict allKeys];

    for (NSString *key in keys){
        NSLog(@"%@",key);
        }

}

1 个答案:

答案 0 :(得分:3)

如果我没弄错,你可以通过下一种方式访问​​这些值:

NSArray *someData = [dict objectForKey:@"SomeData"];
BOOL key1 = [[[someData objectAtIndex:0] valueForKey:@"Key1"] boolValue];
int key2 = [[[[someData objectAtIndex:0] objectForKey:@"Key2"] objectForKey:@"Key3"] intValue];