Illegal attempt to establish a relationship 'xyz' between objects in different contexts

后端 未结 6 1177
傲寒
傲寒 2020-12-23 13:44

I am using Apple\'s CoreDataBooks sample application as a basis for pulling data into a secondary managed object context in the background, and then merging tha

6条回答
  •  情书的邮戳
    2020-12-23 14:28

    Here, you are trying to establish a relation between two objects which are fetched/created with a different context. Core data won't allow you to establish such relations. To achieve this, you should fetch the second object (you are trying to make a relationship with) with the context of the first object with objectID. Now you should be able to establish a relation between these two objects. For example:

    MagicalRecord.saveWithBlock({[unowned self] (localContext: NSManagedObjectContext!) in
    
        let user = User.MR_createEntityInContext(localContext)!
        .....
        .....
    }) //here local context stores data on end of block itself
    
    MagicalRecord.saveWithBlock({[unowned self] (localContext: NSManagedObjectContext!) in
    
        let address = Address.MR_createEntityInContext(localContext)!
        .....
        .....
        let user = localContext.objectWithID(self.user!.objectID) as! User
        user.address = address
    })
    

    Hope this will help you!

提交回复
热议问题