2014-12-02 3 views
0

Что нужно изменить, чтобы предварительно загрузить мой sqlite-файл? Я добавил файл в проект, чтобы заставить меня думать, что я должен внести изменения в этот код.Swift Core Data preload persistentStoreCoordinator:

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 
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("junkapp.sqlite") 
    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.errorWithDomain("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 
}() 
+0

Не можете проголосовать, когда нашли этот учебник для Swift? Некоторое время я искал что-то вроде этого. – martin

+0

Видео youtube, которое я использовал для этого, больше не доступно. – MwcsMac

ответ

1

Просто измените URL-адрес файла, чтобы указать на ваш файл SQLite.

Вам нужно к

  1. копию файла SQLite из пакета в каталог документов.
  2. ссылка этот файл URL в addPersistentStore....

, например.

// Copying 
let path = NSBundle.mainBundle().pathForResource("sqlitefile", ofType:"sqlite")! 
let destinationPath = 
    self.applicationDocumentsDirectory.URLByAppendingPathComponent("junkapp.sqlite")!.path 
NSFileManager.defaultManager().copyItemAtPath(
    path, toPath: destinationPath, error:nil) 

// Using 
coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, 
    configuration: nil, URL: NSURL.fileURLWithPath(destinationPath), 
    options: nil, error: &error) 
+0

Просьба привести пример. – MwcsMac

+0

Что вы пробовали? Проверьте [NSFileManager] (https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/index.html) и [NSBundle] (https://developer.apple.com/ библиотека/ИОС/документация/Какао/Справочные материалы/Foundation/Классы/NSBundle_Class/index.html). – Mundi

+0

NSFileManager.defaultManager(). CopyItemAtPath (путь, toPath: destinationPath, error: nil) Я получаю 'NSURL' не подтип 'NSString' – MwcsMac

0

Это окончательный код, который работал на меня. Обратите внимание на раздел // Копирование и имейте в виду, что перед запуском этого приложения вам придется удалить приложение с устройства или симулятора.

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 
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("junkapp.sqlite") 
    var error: NSError? = nil 
    var failureReason = "There was an error creating or loading the application's saved data." 
    // Copying 
    let path = NSBundle.mainBundle().pathForResource("junkapp", ofType:"sqlite")! 
    NSFileManager.defaultManager().copyItemAtPath(path, toPath: url.path!, error:nil) 
    //end copy 
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: NSURL.fileURLWithPath(url.path!), 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.errorWithDomain("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 
}() 
Смежные вопросы