为什么在重启iOS模拟器时,我的plist变为二进制并丢失其数据

时间:2013-11-03 02:48:29

标签: ios objective-c

我成功地能够为一个plist写一个信息字典。我可以通过执行以下操作来验证这一点:

less /Users/xxxxxx/Library/Application Support/iPhone Simulator/7.0.3-64/Applications/xxxxxxxx/appname.app/myplist.plist

我看到所有以xml格式编写的数据都是我所期望的。 (文件大约1KB)

我关闭了我的模拟器并重新打开它,现在我被告知这个文件是二进制的,它的< 100字节

我对iOS / Objective-c比较陌生,但不确定是否有关于plists以及数据如何持久存在的问题。

1 个答案:

答案 0 :(得分:2)

所以你使用writeToFile:atomically:方法将NSDictionary的数据写入文件,对吧? 如下所示:

static NSString *filename = @"DictFile.plist";
- (NSDictionary *)openDict
{
    NSString *filePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:filename];

    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];

    return dict;
}

- (void)saveDict:(NSDictionary *)dict
{
    NSString *filePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:filename];

    if (![dict writeToFile:filePath atomically:YES])
    {
        [[NSException exceptionWithName:@"IOException"
                             reason:[NSString stringWithFormat:@"filename.plist cannot be saved to %@", filePath]
                           userInfo:nil] raise];
    }

    NSLog(@"File on path: %@", filePath);
}

- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

检查方法:

- (NSDictionary *)createDict
{
    NSDictionary *dict = [self openDict];

    if (dict)
    {
        id key = [[dict allKeys] firstObject];
        if (key)
        {
            NSLog(@"Found dictionary: %@ - %@", key, [dict objectForKey:key]);
        }
    }
    else
    {
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"Key", @"Value", nil];

        [self saveDict:dict];
    }

    return dict;
}