如何在Mac OS X应用程序中为数据库设定种子

时间:2015-10-22 12:24:48

标签: database swift sqlite seed

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

1 个答案:

答案 0 :(得分:0)

我能够弄清楚这一点,所以我想我发布它听别人使用。

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

创建一个函数来处理检查数据库是否已经存在,然后从NSPersistentStoreCoordinator调用if," 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
    }()