我知道这个问题上已经有很多话题,但我似乎找不到能解决我的问题的话题。我有一个以字典为根的 plist,包含三个数组。我写入 plist 的代码在模拟器中运行良好,但在设备上是 (null)。
- 我不是要写入应用程序包,
我的文件路径是正确的,我在启动时检查以确保该文件存在于 Documents 文件夹中(并且确实存在)。
- (void) writeToPlist:(NSString *)fileName playerColor:(NSString *)player withData:(NSArray *)data { NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES); NSString *documentsDirectory = [sysPaths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; NSLog(@"File Path: %@", filePath); NSDictionary *plistDict = [[NSDictionary alloc] initWithContentsOfFile:filePath]; NSLog(@"plist: %@", [plistDict description]); [plistDict setValue:data forKey:player]; BOOL didWriteToFile = [plistDict writeToFile:filePath atomically:YES]; if (didWriteToFile) { NSLog(@"Write to file a SUCCESS!"); } else { NSLog(@"Write to file a FAILURE!"); } }
调试输出:
File Path: /var/mobile/Applications/CA9D8884-2E92-48A5-AA73-5252873D2571/Documents/CurrentScores.plist
plist: (null)
Write to file a FAILURE!
我在其他项目中也使用过同样的方法,所以我不知道我是不是忘记了什么或者是什么原因。我检查了拼写/大写并重新制作了 plist,但都没有任何区别。
那为什么在设备上是plistDict(null),而在模拟器上却没有呢?如果我错过了 plists 上另一篇文章中的解决方案,我深表歉意。
最佳答案
您编写的代码假定该文件已存在于 Documents
文件夹中。第一次调用此方法时不会出现这种情况。
您应该添加一个文件是否存在的检查。如果它在那里,加载它。如果没有,请对您的数据进行其他一些适当的初始化,以准备写入。
此外,您的字典需要可变,以便您更改或添加键/值。
- (void) writeToPlist:(NSString *)fileName playerColor:(NSString *)player withData:(NSArray *)data
{
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES);
NSString *documentsDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSLog(@"File Path: %@", filePath);
NSMutableDictionary *plistDict; // needs to be mutable
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
} else {
// Doesn't exist, start with an empty dictionary
plistDict = [[NSMutableDictionary alloc] init];
}
NSLog(@"plist: %@", [plistDict description]);
[plistDict setValue:data forKey:player];
BOOL didWriteToFile = [plistDict writeToFile:filePath atomically:YES];
if (didWriteToFile) {
NSLog(@"Write to file a SUCCESS!");
} else {
NSLog(@"Write to file a FAILURE!");
}
}
关于ios - (iOS) 从 Documents 文件夹中读取 plist - 我得到正确的路径但无法加载字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16472394/