首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将新应用版本的iOS应用程序数据文件从NSDocumentDirectory移到NSLibraryDirectory?

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

Stack Overflow用户
提问于 2016-06-12 07:13:22
回答 1查看 211关注 0票数 0

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-12 08:32:11

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

代码语言:javascript
复制
...
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37771679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档