对plist进行读/写,文件结构不正确

时间:2014-12-07 11:15:48

标签: ios

我正在尝试学习如何将一些简单的模型对象保存/加载到plist文件中。

模型对象名为“Person”,有2个字符串属性“Name”“Address”

我已将以下内容添加到plist文件中,只是为了测试加载(结构是否正确?):

<plist version="1.0">
<array>
    <dict>
        <key>Name</key>
        <string>name1</string>
        <key>Address</key>
        <string>address1</string>
    </dict>

    <dict>
        <key>Name</key>
        <string>name2</string>
        <key>Address</key>
        <string>address2</string>
    </dict>
</array>
</plist>

我像这样加载

 -(void)load
{

    NSError *error;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: [self plistPath]]) 

    {

        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; //5

        [fileManager copyItemAtPath:bundle toPath: [self plistPath] error:&error]; /
    }
     NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: [self  plistPath]];

     NSLog(@"%lu",(unsigned long)savedStock.count);
}

-(NSString*)plistPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1

    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    return [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; 
}

但是我如何获得封装包含我的实际数据的字典的数组呢?

1 个答案:

答案 0 :(得分:2)

你保存的plist是NSArray,所以你应该像NSArray那样取回它。

NSArray *savedArray = [NSArray arrayWithContentsOfFile:[self  plistPath]];