ios - 新应用程序版本的 iOS 应用程序数据文件应如何从 NSDocumentDirectory 移动到 NSLibraryDirectory?

标签 ios nsfilemanager nsdocumentdirectory app-update nslibrarydirectory

在我的应用程序的当前版本中,我在 NSDocumentDirectory 中存储了两个重要的应用程序文件(我的核心数据 .sqlite 文件和我的 SettingsFile.plist)。在下一个版本中,我想将这些文件移动到 NSLibraryDirectory。两者都不需要用户直接访问进行编辑,根据我的研究,这似乎是每个文件的最佳选择。

我关心的是如何将所有当前应用程序用户的文件从 NSDocumentDirectory 移动到 NSLibraryDirectory。我要非常小心不要丢失任何用户数据。我不知道从哪里或如何开始以一种非常安全的方式移动这些文件。我希望有人能指出我正确的方向。

最佳答案

您可以使用 NSFileManager 检查文件是否已存在于库文件夹中,如果不存在,请移动它们。如果移动成功,删除旧文件并返回新路径,如果不成功,返回旧路径。见下文:

...
NSString *mySQLfilePath = [self getFilePathWithName:@"database.sqlite"];
...

- (NSString *)getFilePathWithName:(NSString *)filename
{
    NSString *libPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

    NSString *fileLibPath = [libPath stringByAppendingPathComponent:filename];
    NSString *fileDocPath = [docPath stringByAppendingPathComponent:filename];

    if ([[NSFileManager defaultManager] fileExistsAtPath:fileLibPath]) {
        // file already exists in Library folder
        return fileLibPath;

    } else if ([[NSFileManager defaultManager] fileExistsAtPath:fileDocPath]) {
        // file exists in Documents folder, so move it to Library
        NSError *error = nil;
        BOOL moved = [[NSFileManager defaultManager] moveItemAtPath:fileDocPath toPath:fileLibPath error:&error];
        NSLog(@"move error: %@", error);

        // if file moved, you can delete old Doc file if you want
        if (moved) [self deleteFileAtPath:fileDocPath];

        // if file moved successfully, return the Library file path, else, return the Documents file path
        return moved ? fileLibPath : fileDocPath;
    }

    // file doesn't exist
    return nil;
}

- (void)deleteFileAtPath:(NSString *)filePath
{
    if ([[NSFileManager defaultManager] isDeletableFileAtPath:filePath]) {
        NSError *error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        NSLog(@"delete error: %@", error);

    } else {
        NSLog(@"can not delete file: %@", filePath);
    }
}

如有疑问,请随意。仅供访客引用:

https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html

关于ios - 新应用程序版本的 iOS 应用程序数据文件应如何从 NSDocumentDirectory 移动到 NSLibraryDirectory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37771679/

相关文章:

iphone - 将 NSData 写入桌面文件

ios - 文档目录中的图像数组

ios - 同时使用不同的动画曲线对自动布局约束进行动画处理

ios - 如何从Apple获取崩溃日志?

swift - 在 Foundation 中找不到 FileManager Swift 类,它在哪里?

iphone - iPhone 中我的目录路径中的文件夹名称

ios - 无法在 iMessage 扩展中显示文档目录中的贴纸

ios - 当 NSDictionary 添加到数组中时,它会替换之前的字典

ios - 在不覆盖 iPhone 上的当前 View 的情况下呈现模态视图 Controller

ios - 使用台风注入(inject)单例提供多个实例