在ios应用程序中保存sqlite数据库文件(.db)的更好方法

时间:2014-04-07 06:08:05

标签: ios iphone sqlite

在ios应用程序中复制sqlite数据库文件(.db)的更好方法是在NSBundle或Document文件夹中。

1 个答案:

答案 0 :(得分:0)

你可以试试这个

- (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:@"DB.sqlite"];
    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:@"KURANDB2.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}