在哪里将您的SQLite数据库文件在iPhone应用程序?

前端之家收集整理的这篇文章主要介绍了在哪里将您的SQLite数据库文件在iPhone应用程序?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我最初为我的应用程序创建一个带有预先插入的数据集的sqlite数据库文件时,我必须将这个文件放在我的Xcode项目中的某个位置,以便它进入我的iPhone应用程序。我想“资源”是正确的地方。

在iPhone应用程序中部署sqlite数据库文件的基本“步骤”是什么?

>手动创建数据库
>将数据库文件添加到项目(其中?)

我目前正在阅读整个sqlite文档,虽然这不是很多iPhone相关。

@H_301_8@
@H_301_8@
您需要首先将sqlite文件添加到您的Xcode项目 – 最适当的地方是在资源文件夹中。

然后在您的应用程序委托代码文件中,在appDidFinishLaunching方法中,您需要首先检查是否已经创建了sqlite文件的可写副本 – 例如:已在用户文档文件夹中创建了sqlite文件的副本iPhone的文件系统。如果是,你不做任何事情(否则你会用默认的Xcode sqlite复制它)

如果没有,那么你复制sqlite文件在那里 – 使其可写。

看下面的代码示例来做:这是从苹果的sqlite书代码示例,其中此方法从应用程序委派appDidFinishLaunching方法调用

// 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]);
    }
}

============

这里是上面的代码在Swift 2.0

// Creates a writable copy of the bundled default database in the application Documents directory.
private func createEditableCopyOfDatabaseIfNeeded() -> Void
{
    // First,test for existence.
    let fileManager: NSFileManager = NSFileManager.defaultManager();
    let paths:NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)
    let documentsDirectory:NSString = paths.objectAtIndex(0) as! NSString;
    let writableDBPath:String = documentsDirectory.stringByAppendingPathComponent("bookdb.sql");

    if (fileManager.fileExistsAtPath(writableDBPath) == true)
    {
        return
    }
    else // The writable database does not exist,so copy the default to the appropriate location.
    {
        let defaultDBPath = NSBundle.mainBundle().pathForResource("bookdb",ofType: "sql")!

        do
        {
            try fileManager.copyItemAtPath(defaultDBPath,toPath: writableDBPath)
        }
        catch let unknownError
        {
            print("Failed to create writable database file with unknown error: \(unknownError)")
        }
    }
}
@H_301_8@ 原文链接:https://www.f2er.com/sqlite/198135.html

猜你在找的Sqlite相关文章