Master data passing objectID to another stream

I tried Google and searched SO thinking it would be pretty easy to find, but I'm surprised Swift didn't have examples of my problem.

I have multiple threads and from what I've read it is best to have a separate managed object context for each thread. If I want to access an object from a different context, I have to go around objectID

.

My question is, how do I pass an ID object to a context on a new thread?

Here's how to build my situation:

func doSomething(context: NSManagedObjectContext) {
    let person = Persons(context: context) // NSManagedObject

    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
        let background = (UIApplication.sharedApplication().delegate as! AppDelegate).cdh.backgroundContext!

        Birthdays(context: background, person) // NSManagedObject
        saveContext(background)
    }
}

      

Birthdays have individual relationships with people. If I execute this code it gives me an error:

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

      

Obviously because they are in separate contexts. So I tried to get the objectID person1

on let personsObjectID = person1.objectID

, but I don't know how I should use it to pass it to another thread. Any help is appreciated.

+3


source to share


2 answers


It seems the only thing I needed to do was add:

let person = background.objectWithID(orders.objectID as! Persons

      



If I understand correctly, objectWithID

retrieves an object from storage and puts it into the context, returning a managed object. It would be nice if someone could check this if it's true.

func doSomething(context: NSManagedObjectContext) {
    let person = Persons(context: context) // NSManagedObject

    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
        let background = (UIApplication.sharedApplication().delegate as! AppDelegate).cdh.backgroundContext!

        let person = background.objectWithID(orders.objectID as! Persons

        Birthdays(context: background, person) // NSManagedObject
        saveContext(background)
    }
}

      

+1


source


Hendrick, you are correct, you have to use objectWithID to instantiate NSManagedObject in the required context.



0


source







All Articles