初始化NSPersistentStore对象

时间:2017-01-12 16:52:54

标签: ios swift xcode core-data swift3

Swift版本:swift3.0 目标iOS版本:10.0

我尝试为涉及核心数据的函数编写单元测试。所以我想要做的第一件事就是使用NSPersistentStore类型初始化类变量。

这是我的类变量

的代码
class DataProviderTests: XCTestCase {
    var storeCoordinator: NSPersistentStoreCoordinator!
    var managedObjectContext: NSManagedObjectContext!
    var managedObjectModel: NSManagedObjectModel!
    var store: NSPersistentStore!
    .....
}

及以下是初始化类变量的设置函数

override func setUp() {
    super.setUp()

    managedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil)
    storeCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
    do{
        try store = storeCoordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil)
    }catch let error as NSError{
        print(error)
        store = nil
    }
    .....
}

但问题是Xcode一直在抱怨该类没有初始化器。

Swift Compiler Error: Class 'DataProviderTests' has no initializers

我发现'store'变量未正确初始化。

但是addPersistanteStoreWithtype()函数可以抛出错误,我应该使用try和catch子句。但它导致了这个问题..

初始化商店类变量以解决问题的最佳方法是什么?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

以下是适用于我的try - catch执行示例:

func getDocumentsURL() -> URL {
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    return documentsURL
}

var modelUrl: URL? // This would be the unique URL for your data model

let storeUrl:URL = getDocumentsURL().appendingPathComponent("<YOURNAME.sqlite>") // Make sure to update with your project name or whatever your sqlite filename is

var persistentStoreCoordinator: NSPersistentStoreCoordinator!

var store: NSPersistentStore!

var error: Error? // Use to handle error in case of failure

if let modelAtUrl = NSManagedObjectModel(contentsOf: modelUrl) {

     managedObjectModel = modelAtUrl

     persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)

     let options = [
         NSMigratePersistentStoresAutomaticallyOption: true,
         NSInferMappingModelAutomaticallyOption: true
     ]

     managedObjectContext = NSManagedObjectContext(concurrencyType: concurrencyType)
     managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator

     do {
         try store = self.persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: storeUrl, options: options)
        } catch let error as Error {
         print("Unable to initialize persistent store coordinator:", error)
         self.error = error
     } catch {
         fatalError()
     }

} else {
     fatalError("Error initializing managed object model from URL: \(modelUrl)")
}