gpt4 book ai didi

ios - 初始化 NSPersistentStore 对象

转载 作者:行者123 更新时间:2023-11-30 12:46:11 28 4
gpt4 key购买 nike

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 子句。但这会导致这个问题..

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

感谢您的帮助

最佳答案

这是一个适合我的 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)")
}

关于ios - 初始化 NSPersistentStore 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41618771/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com