gpt4 book ai didi

swift - 核心数据在不同线程中获取和保存

转载 作者:行者123 更新时间:2023-11-30 11:41:39 24 4
gpt4 key购买 nike

我创建了一个 Coredatacontroller 类来处理所有核心数据操作。该类中编写了一种获取当前上下文的方法。

func getCurrentContext() -> NSManagedObjectContext {
var curMOC:NSManagedObjectContext? = self.managedObjectContext
let thisThread:Thread = Thread.current
print("This thread: ", thisThread)
if thisThread == Thread.main {
if curMOC != nil {
return curMOC!
}
let coordinator:NSPersistentStoreCoordinator? = self.persistentStoreCoordinator
if coordinator != nil {
curMOC = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
curMOC?.persistentStoreCoordinator = coordinator
}
return curMOC!
}
// if this is some other thread....
// Get the current context from the same thread..
var threadManagedObjectContext:NSManagedObjectContext? = thisThread.threadDictionary.object(forKey:"MOC_KEY") as? NSManagedObjectContext;
// Return separate MOC for each new thread
if threadManagedObjectContext != nil {
return threadManagedObjectContext!;
}

let coordinator:NSPersistentStoreCoordinator? = self.persistentStoreCoordinator
if coordinator != nil {
threadManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
threadManagedObjectContext?.persistentStoreCoordinator = coordinator
threadManagedObjectContext?.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
thisThread.threadDictionary.setObject(threadManagedObjectContext!, forKey: "MOC_KEY" as NSCopying)
}
return threadManagedObjectContext!;
}

我正在使用 NSOperation 子类上传一些图像,因此对于每个图像都会创建一个 NSOperation 对象。在 NSOperation 的完成 block 内,我从 CoreData 获取一些数据并更新它。

问题:提取不会返回核心数据中存在的记录如果在获取方法中我使用 mainmanagementobjectcontext,那么我会获取记录,但是当我使用 currentcontext 保存它时,它不会反射(reflect)对核心数据的更改。我也在 NSOperation 子类中编写了通知观察者方法,但该方法从未被调用。请建议应该做什么!!

最佳答案

处理来自不同线程的 CoreData 对象非常复杂。我建议使用CoreStore ,它将为您完成所有上下文处理。

设置示例:

let dataStack: DataStack = {
let dataStack = DataStack(xcodeModelName: "ModelName")
do {
try dataStack.addStorageAndWait()
} catch let error {
print("Cannot set up database storage: \(error)")
}
return dataStack
}()

对象创建示例:

func addUser(id: String, name: String) {
dataStack.perform(asynchronous: { transaction in
let user = transaction.create(Into<User>())
user.id = id
user.name = name
}, completion: { _ in })
}

对象获取示例:

func printUserName(id: String) {
dataStack.perform(asynchronous: { transaction in
guard let user = transaction.fetchOne(From<User>(), Where("id", isEqualTo: id) else {
return
}
print(user.name)
}, completion: { _ in })
}

关于swift - 核心数据在不同线程中获取和保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49230513/

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