我成功地将信息字典写入 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 的新手,但不确定我是否从根本上缺少关于 plist 以及数据如何持久化的内容。
最佳答案
所以你使用 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;
}
关于ios - 为什么在重新启动 iOS 模拟器时我的 plist 变成二进制并丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19749349/