gpt4 book ai didi

ios - 使用writeToFile保存文件

转载 作者:行者123 更新时间:2023-12-01 18:46:36 25 4
gpt4 key购买 nike

因此,我发现了使用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);
});

});

关于ios - 使用writeToFile保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com