我有一個類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")
非法嘗試建立在 不同的上下文對象之間的關係
如何保存產品的fk字段?
請注意,您不應該在私有上下文中設置「persistenStoreCoordinator」(不建議使用)。相反,設置'parentContext'。 – Mundi