Как следует перемещать файлы данных приложения iOS для новой версии приложения из NSDocumentDirectory в NSLibraryDirectory?

В текущей версии моего приложения я сохранил два важных файла приложения (мой файл Core Data .sqlite и мой файл SettingsFile.plist) в NSDocumentDirectory. В следующей версии я хочу переместить эти файлы в NSLibraryDirectory. Ни один из них не нуждается в прямом доступе пользователя для редактирования, и мое исследование показало, что это лучший вариант для каждого из этих файлов.

Меня беспокоит, как переместить файлы для всех моих текущих пользователей приложения из NSDocumentDirectory в NSLibraryDirectory. Я хочу быть очень осторожным, чтобы не потерять данные пользователей. Я не знаю, где и как начать перемещать эти файлы очень безопасным способом. Я надеюсь, что кто-то может указать мне в правильном направлении.


person SAHM    schedule 12.06.2016    source источник
comment
Разве вы не можете просто проверить, находится ли файл в каталоге библиотеки, и если да, используйте его оттуда, а если он находится в каталоге документов, переместите его и затем начните использовать? Я не понимаю сложности.   -  person Droppy    schedule 12.06.2016


Ответы (1)


Вы можете использовать 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

person emotality    schedule 12.06.2016
comment
[NSHomeDirectory() stringByAppendingPathComponent:@"Library"];? Я так не думаю... - person Droppy; 12.06.2016
comment
NSHomeDirectory(): /Application/DAF1FB3A-3ED3-464C-AAEB-CC21F3761355 NSLibraryDirectory: /Application/DAF1FB3A-3ED3-464C-AAEB-CC21F3761355/Library NSDocumentsDirectory: /Application/DAF1FB3A-3ED3-464C-AAEB-CC21F3761355/Documents - person emotality; 12.06.2016
comment
Вы должны использовать NSSearchPathForDirectoriesInDomains. - person Droppy; 12.06.2016
comment
Это то же самое. Зачем иметь массив, а затем выбирать единственный объект [0], если вы можете просто использовать вышеуказанное? - person emotality; 12.06.2016
comment
Потому что это то, что он говорит вам использовать в ссылке, которую вы предоставляете. - person Droppy; 12.06.2016