我创建了CoreData堆栈的模拟版本
import Foundation
import CoreData
@testable import Companion
final class MockedDatabaseStackController: DatabaseStackControllerProtocol {
let batchRequestsAvailable: Bool = false
private lazy var managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle(for: type(of: self))])!
lazy var persistentContainer: NSPersistentContainer = {
let description = NSPersistentStoreDescription()
description.type = NSInMemoryStoreType
description.shouldAddStoreAsynchronously = false
let container = NSPersistentContainer(
name: "database",
managedObjectModel: managedObjectModel
)
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { description, error in
// Check if the data store is in memory
precondition( description.type == NSInMemoryStoreType )
// Check if creating container wrong
if let error = error {
fatalError("Create an in-mem coordinator failed \(error)")
}
}
return container
}()
init() {
NotificationCenter.default
.addObserver(
self,
selector: #selector(didManagedObjectContextSave(notification:)),
name: .NSManagedObjectContextDidSave,
object: nil
)
}
@objc
private func didManagedObjectContextSave(notification: Notification) {
DispatchQueue.main.async { [weak self] in
self?.persistentContainer.viewContext.mergeChanges(fromContextDidSave: notification)
}
}
}
我正在用它来保存一些对象:
private func executeAndSave<T>(_ executionBlock: @escaping ((NSManagedObjectContext) throws -> T)) -> Single<T> {
let persistentContainer = stackController.persistentContainer
return Single.create { observer in
persistentContainer.performBackgroundTask { context in
do {
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
jsons.forEach {
let mo = type.init(context: context)
mo.update(withGatewayResponse: $0)
}
try context.save()
DispatchQueue.main.async {
observer(.success(result))
}
} catch {
DispatchQueue.main.async {
observer(.error(error))
}
}
}
return Disposables.create()
}
}
func save(jsons: [JSON], as type: GatewayObjectDeserializableAndSavable.Type) -> Single<Void> {
if jsons.isEmpty {
log.info("(\(type)) Nothing to save.")
return .just(())
}
log.info("DatabaseHelper will save \(type)")
return executeAndSave { context in
jsons.forEach {
let mo = type.init(context: context)
mo.update(withGatewayResponse: $0)
}
}
}
// Example of usage:
databaseHelper.save(jsons: jsons, as: Herd.self)
请注意,在我使用此CoreData堆栈的主要目标中,一切正常:
final class DatabaseStackController: DatabaseStackControllerProtocol {
// singleton
static let controller = DatabaseStackController()
private static let kDatabaseName = "database"
let persistentContainer: NSPersistentContainer = DatabaseStackController.buildDatabaseStack(onComplete: nil)
let batchRequestsAvailable: Bool = true
private init() {
addNSMangedObjectContextObservers()
}
private static func buildDatabaseStack(onComplete: (() -> Void)?) -> NSPersistentContainer {
let container = NSPersistentContainer(name: kDatabaseName)
container.loadPersistentStores { _, error in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
onComplete?()
}
return container
}
}
为什么不起作用? NSInMemoryStoreType
是否不支持CoreData的约束?有可能修复它吗?
答案 0 :(得分:1)
我认为您在Core Data中发现了一个错误:(
我有一个有关Core Data的 Unique Constraint 的小演示项目。我确认它可以按预期运行except for some exceptions,并且始终将所有重复项与SQLite存储合并。然后,我粘贴到您的MockedDatabaseStackController
类中,并将其persistentContainer.viewContext
与NSMergeByPropertyObjectTrumpMergePolicy
集一起使用。结果:似乎在第一个 save 操作上合并了第一组重复项,但此后没有合并。然后,除了将存储类型更改为NSInMemoryStoreType
之外,我再切换回我的Core Data堆栈。结果:它也无法正常工作,与您的MockedDatabaseStackController
一样。
Core Data的SQLite存储基础的SQLite数据库在its SQL中支持 UNIQUE 约束。我希望有人能证明我错了,但是,可悲的是,我怀疑Apple使用SQLite的此功能在Core Data中实现了 Unique Constraint 功能,但未能将事实添加到their documentation中只能用于SQLite存储。
我已将其提交给Apple Bug Reporter:50725935。
对于您的测试,我认为您应该对其进行修改以创建临时的SQLite存储。实际上,Venn图的另一端有一些功能-内存存储支持,SQLite存储不支持。在内存中进行测试可能会在测试范围中留下漏洞。