gpt4 book ai didi

ios - 线程中的核心数据保存对象与关系

转载 作者:可可西里 更新时间:2023-11-01 01:37:57 24 4
gpt4 key购买 nike

我有一个类 Store,其方法 fetchProducts 在后台工作并从 json 数据保存产品。

class Store: NSManagedObject {

func fetchProducts(q: String) {
....
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
self.saveProduct(json_data)
}
}
}

}

在这个类中,我有一个方法 saveProduct 检查产品是否存在,然后这个产品应该更新或创建新的:

func saveProduct(data:[String: String]) -> Bool {
var product:Product
var products = self.products.allObjects as! [Product]
if (self.managedObjectContext == nil) {
return false
}

if (data["storeName"] != nil) {
products = products.filter{ $0.storeName == data["storeName"] }
} else {
return false
}

let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.persistentStoreCoordinator = self.managedObjectContext!.persistentStoreCoordinator

if (data["storeName"] != nil) {
products = products.filter{ $0.storeName == data["storeName"] }
} else {
return false
}
if products.count > 0 {
product = products.first!
} else {
if let productEntity = NSEntityDescription.entityForName("Product", inManagedObjectContext: privateContext) {
product = Product(entity: productEntity, insertIntoManagedObjectContext: privateContext)
} else {
return false
}
}

product.setValue(data["storeName"], forKey: "storeName")
product.setValue(data["storeType"], forKey: "storeType")
product.setValue(self, forKey: "shopItem")
privateContext.performBlockAndWait {
do {
try privateContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}

}

return true
}

但我收到此行的错误:product.setValue(self, forKey: "shopItem")

Illegal attempt to establish a relationship between objects in different contexts

如何保存产品的 fk 字段?

最佳答案

如果你运行 product = products.first!那么您使用的是来自与“ self ”相同上下文的原始产品。该上下文与 privateContext 不同因此您的保存实际上不会保留更改。

如果你运行 product = Product(entity:...那么您正在使用 privateContext 中的新产品这与 self 的上下文不同.

你真正应该做的是过滤当前线程并使用 objectIDprivateContext 中查找匹配项,或对 privateContext 进行过滤提取.通过这种方式,您始终在 privateContext 中拥有产品.然后你需要使用 self.objectID得到selfprivateContext这样您就可以更新关系并保存。

这都是维持线程限制所必需的。

确实,您还应该运行 this is performBlock (或等待版本)以便上下文可以在其私有(private)队列中运行逻辑。

关于ios - 线程中的核心数据保存对象与关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33499514/

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