我有一個購物車控制器。用戶可以將項目添加到他的願望清單。如果我們沒有任何願望清單,我們應該創建默認的清單。這是工程2-3次,如果我添加,然後刪除,然後再添加。然後我得到的錯誤:爲什麼在一個視圖中有不同的上下文?
Illegal attempt to establish a relationship 'wishList' between objects in different contexts
class CartViewController: UIViewController, NSFetchedResultsControllerDelegate {
var fetchResultController:NSFetchedResultsController!
var shopItems:[ShopItem] = []
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
self.fetchResultController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: self.appDelegate.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
self.fetchResultController.delegate = self
do {
try fetchResultController.performFetch()
self.shopItems = fetchResultController.fetchedObjects as! [ShopItem]
} catch {
fatalError("Failure to save context: \(error)")
}
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let addToWishListAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Add to wish list", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
var wishListResults:[WishList] = []
let fetchRequest = NSFetchRequest(entityName: "WishList")
var wishList:WishList
fetchRequest.fetchLimit = 1
//...some other code
wishList = NSEntityDescription.insertNewObjectForEntityForName("WishList", inManagedObjectContext: self.appDelegate.managedObjectContext) as! WishList
wishList.setValue("Default wish list", forKey: "title")
wishList.setValue("My wish list", forKey: "desc")
let shopItem = self.fetchResultController.objectAtIndexPath(indexPath) as! ShopItem
shopItem.setValue(true, forKey: "inWishList")
shopItem.setValue(wishList, forKey: "WishList")
do {
try self.appDelegate.managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
})
}
}
爲什麼語境變了嗎?
>此外,確保你所創建的ManagedObjectContext作爲使用MainQueueConcurrencyType: 你的意思替換此: '''讓的appDelegate = UIApplication.sharedApplication()DELE門作爲! AppDelegate''' ??因爲我在每個控制器中使用它?這是正常的嗎? – Arti
現在我每次都會收到錯誤'''非法嘗試建立關係''。這沒有幫助 – Arti
這個答案實際上並沒有解決線程問題,真正的問題是你在2個上下文中混合對象 – Wain