2

我正在尝试将一个保存到NSMutableDictionary一个文件中。保存后立即尝试检查文件是否存在并读回,但找不到文件。applicationDidEnterBackgroundAppDelegate.mplist

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");
}
4

3 回答 3

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
于 2013-06-19T13:00:03.687 回答
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];
于 2013-06-19T12:57:49.993 回答
0

在 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
}
于 2016-10-29T11:30:47.397 回答