0

我成功地将信息字典写入 plist。我可以通过执行以下操作在运行应用程序时验证这一点:

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

我看到所有数据都以 xml 格式写入,正如我所期望的那样。(文件大约 1KB)

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

我对 iOS / Objective-c 比较陌生,但不确定我是否从根本上缺少关于 plist 和数据如何持久化的东西。

4

1 回答 1

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;
}
于 2013-11-03T06:30:05.163 回答