database - 如何在 Mac OS X 应用程序中播种数据库

标签 database swift sqlite seed

我想将存储在应用程序包中的 sqlite 数据库添加到 Mac OS X 中的应用程序数据存储文件路径,如何使用 Apple 的新 Swift 编程语言来实现?

最佳答案

我能够弄清楚这一点,所以我想我会把它贴出来供其他人使用。

使用应用程序包中的 Swift 将数据库种子到 Mac OS X 应用程序:

创建一个函数来处理检查数据库是否已经存在,然后如果从 NSPersistentStoreCoordinator 调用,“DBName”是您的数据库的名称:

func openDB()
{

    let storePath = applicationDocumentsDirectory.URLByAppendingPathComponent(“DBName.sqlite").path
    let dataPath = NSBundle.mainBundle().pathForResource(“DBName", ofType: "sqlite")
    //let testPath = storePath.path
    //let testPath2 = storePath
    if !NSFileManager.defaultManager().fileExistsAtPath(storePath!)
    {
        do
        {
            try NSFileManager.defaultManager().copyItemAtPath(dataPath!, toPath: storePath!)
        } // end do
        catch
        {
            NSLog("Error copying database file")
        } // end catch
    } // end if
} // end openDB

我在 NSPersistentStoreCoordinator 中调用它,所以它只被调用一次

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {

应用程序的持久存储协调器。此实现创建并返回一个协调器,已将应用程序的商店添加到它。此属性是可选的,因为存在可能导致存储创建失败的合法错误条件。

    // Create the coordinator and store
    self.openDB()
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent(storeFilename)
    var failureReason = "There was an error creating or loading the application's saved data."
    do
    {
        //try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
        try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: [NSMigratePersistentStoresAutomaticallyOption: true,
            NSInferMappingModelAutomaticallyOption: true])
    }
    catch
    {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason

        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: domainName, code: 9999, userInfo: dict)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }

    return coordinator
    }()

关于database - 如何在 Mac OS X 应用程序中播种数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281002/

相关文章:

mysql - 如果列名/字段名存在于 mySQL 的表中,则搜索数据库

ios - swift promise 套件 : Equivalent to when() which executes sequentially?

swift - swift 条件编译的案例陈述

sql - 如何找出 sqlite 数据库中的记录 (BLOB) 使用了多少物理空间?

linux - 链接 ARM 上的 SQLite3(x86_64 主机)

performance - 运行 sqlite 查询后如何加快获取结果的速度?

database - Oracle直方图和读取错误索引

c++ - 用于在 C++ 中抽象数据库访问的开源库?

sql - 连接到 oracle 数据库的 cfprocparam 未返回 sid

ios - Swift 取消 ActivityViewController 导致 fatal error