使用 writeToFile 保存文件

Saving files using writeToFile

所以我发现了一个小问题,即使用 writeToFile 保存数组以便稍后检索它。我正在使用:

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        if ([paths count] > 0)
        {
            NSString *arrayPath = [[paths objectAtIndex:0]
                         stringByAppendingPathComponent:@"array.out"];

            [finalSavedArray writeToFile:arrayPath atomically:YES];
            [[NSUserDefaults standardUserDefaults] setObject:arrayPath forKey:@"SavedArrayPath"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }

将 'finalSavedArray' 保存为文件,稍后使用以下方法检索此数组:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSLog(@"File path: %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"SavedArrayPath"]);
        NSMutableArray *savedArray = [NSMutableArray arrayWithContentsOfFile:[[NSUserDefaults standardUserDefaults] objectForKey:@"SavedArrayPath"]];
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"SAVED ARRAY:%@",savedArray);
        });

    });

当我在保存文件后立即访问文件时,这工作正常,但是当我重新启动应用程序时,数组显示为空,似乎在保存的目录中找不到。从一些阅读来看,这个文件目录似乎应该是相对的,因为每次你打开应用程序时我现在保存的目录都会改变,但我还不太清楚如何更改我的代码为了将其保存到相对目录。任何帮助将不胜感激:)

应用的路径可以改变。永远不要存储文件的绝对路径。在您的情况下,只需存储相对于 Documents 文件夹的路径。

当你想读取文件时,从NSUserDefaults读取相对路径,然后像写入文件一样重建完整路径。

正在写入文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0)
{
    NSString *arrayPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"array.out"];

    [finalSavedArray writeToFile:arrayPath atomically:YES];
    [[NSUserDefaults standardUserDefaults] setObject:[arrayPath lastPathComponent] forKey:@"SavedArrayPath"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

正在读取文件:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filename = [[NSUserDefaults standardUserDefaults] objectForKey:@"SavedArrayPath"];
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:filename];
    NSMutableArray *savedArray = [NSMutableArray arrayWithContentsOfFile:path];
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSLog(@"SAVED ARRAY:%@",savedArray);
    });

});