Копирование файлов в каталог документов приложений, контроль ошибок - PullRequest
1 голос
/ 16 февраля 2012

Я видел этот пост, который был полезен при копировании файла .db, который я включаю в свое приложение, и скопировал его в соответствующий каталог: Где бы вы разместили файл базы данных SQLite в приложении iPhone?

Предоставляет ли метод, который работает, какой-либо тип обработки ошибок или ошибок? Например, если пользователь думал, что приложение зависло из-за пересылки слишком долго, и решил принудительно закрыть приложение?

Метод:

// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"bookdb.sql"];
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success)
        return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bookdb.sql"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

1 Ответ

1 голос
/ 16 февраля 2012

Нет, ничего не происходит, если существует существующий файл с таким же именем.

Так что, если копирование по какой-то причине было прервано в середине, то при следующем запуске он подумаетфайл уже там.

Возможно, вам следует сначала выполнить копирование во временный файл, а затем, если он завершится, переименовать его в нужное имя.

BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

// Getting the writable path of the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"bookdb.sql"];

// Checking if the file exists at the writable path
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
    return;

// Incase the file does not exist
// Getting the temporary path of the file
NSString *tempDBPath = [documentsDirectory stringByAppendingPathComponent:@"bookdb_temp.sql"];

// Just making sure no temporary file exists from a previous operation
success = [fileManager fileExistsAtPath:tempDBPath];
if (success)
{
    success=[fileManager removeItemAtPath:tempDBPath error:&error];
    NSAssert1(success, @"Failed to delete temp database file with message '%@'.", [error localizedDescription]);
}

// Getting the default path of the file
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bookdb.sql"];

// Copying the file from the default path to the temporary
NSLog(@"Starting to copy");
success = [fileManager copyItemAtPath:defaultDBPath toPath:tempDBPath error:&error];
NSAssert1(success, @"Failed to copy database file with message '%@'.", [error localizedDescription]);
NSLog(@"Finished copying");

// Renaming the temporary file which wouldn't take time but to ensure the copying has finished successfully
success= [fileManager moveItemAtPath:tempDBPath toPath:writableDBPath error:&error];
NSAssert1(success, @"Failed to rename temp database file with message '%@'.", [error localizedDescription]); 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...