[英](iOS) Reading a plist from Documents folder - I get correct path but can't load dictionary
我知道在这个问题上已经有很多线程,但我似乎无法找到解决我问题的线程。 我有一个以词典为根的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!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.