我正在尝试将NSMutableDictionary
applicationDidEnterBackground
个AppDelegate.m
中的plist
保存到NSString *photoCacheFilename = @"photoCache.plist";
[photoDict writeToFile:photoCacheFilename atomically:YES];
NSLog(@"File name: %@", photoCacheFilename);
BOOL isFile = [[NSFileManager defaultManager] fileExistsAtPath:photoCacheFilename];
if(isFile)
{
NSLog (@"File found");
NSMutableDictionary *newDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:photoCacheFilename];
}
else
{
NSLog (@"File not found");
}
文件中。保存后,我立即尝试检查文件是否存在并将其读回,但找不到该文件。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *photoCacheFilename = [documentsPath stringByAppendingPathComponent:@"photoCache.plist"];
[photoDict writeToFile:photoCacheFilename atomically:YES];
BOOL isFile = [[NSFileManager defaultManager] fileExistsAtPath:photoCacheFilename];
if(isFile)
{
NSLog (@"File found");
NSMutableDictionary *newDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:photoCacheFilename];
}
else
{
NSLog (@"File not found");
}
我按照某些用户的建议修改了代码,但仍未找到该文件。我不确定我是否正确检查文件是否存在。
{{1}}
答案 0 :(得分:4)
您没有指定Documents
目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *photoCacheFilename = [documentsPath stringByAppendingPathComponent:@"photoCache.plist"]; // Correct path to Documents Dir in the App Sand box
[photoDict writeToFile:photoCacheFilename atomically:YES]; //Write
答案 1 :(得分:1)
您必须指定保存数据的完整路径:
NSString *myFile = @"myFile.plist";
NSArray *filePaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [filePaths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:myFile];
[photoDict writeToFile:path atomically:YES];
答案 2 :(得分:0)
IN SWIFT 3.0
获取文档目录中的photoCache.plist文件路径。
func getPath() -> String {
let plistFileName = "photoCache.plist"
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentPath = paths[0] as NSString
let plistPath = documentPath.appendingPathComponent(plistFileName)
return plistPath
}
检查文件是否存在。
let plistPath = self.getPath()
if FileManager.default.fileExists(atPath: plistPath) {
//File Exists
}