iOS - 将预先填充的数据库添加到Core Data

时间:2014-09-20 17:40:33

标签: ios sqlite core-data

我知道这个问题已经被问过很多次了,我想我已经阅读了所有问题,但我仍然无法解决我的错误。这是我的代码:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    let storePath = self.applicationDocumentsDirectory.path?.stringByAppendingPathComponent("name.sqlite")
    let fileManager : NSFileManager = NSFileManager.defaultManager()
    var fileCopyError:NSError? = NSError()
    if !fileManager.fileExistsAtPath(storePath!) {
        let defaultStorePath : NSString! = NSBundle.mainBundle().pathForResource("name", ofType: "sqlite")
        if((defaultStorePath) != nil) {
            println("copying")
            fileManager.copyItemAtPath(defaultStorePath, toPath: storePath!, error: &fileCopyError)
        }
    }
    var coordinator: NSPersistentStoreCoordinator?
    coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = NSURL(fileURLWithPath: storePath!)
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
        coordinator = nil
        // Report any error we got.
        let dict = NSMutableDictionary()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        error = NSError(domain: "YOUR_ERROR_DOMAIN", 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 \(error), \(error!.userInfo)")
        abort()
    }

    return coordinator
}()

问题是它使用我使用的名称复制.sqlite文件但是为空。

编辑:仅供参考我已经清理了构建文件夹并重置了iPhone模拟器。

0 个答案:

没有答案