Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data passing objectID to another thread

I've tried Googling and searching SO, thinking it would be quite easy to find but I'm surprised there were little to no examples of my problem in Swift.

I have several threads and from what I've read, it's best to have a separate managed object context for each thread. If I want to access an object from another context, I should pass around the objectID.

My question is, how should I pass the objectID to the context in a new thread?

Below is how the construction of my situation is:

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 has a one to one relationship with Persons. If I execute this code it will give me an error saying:

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

Obviously because they are in separated contexts. So I tried to get the objectID of person1 by let personsObjectID = person1.objectID, but I don't know how I should be using it to pass it to the other thread. Any help is appreciated.

like image 941
Hendrik Smoels Avatar asked Nov 19 '25 13:11

Hendrik Smoels


1 Answers

Seems like the only thing I needed to do was to add:

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

If I've understood it correctly, objectWithID fetches the object from the store and puts it in the context, returning the managed object. It would be nice if someone could verify 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)
    }
}
like image 55
Hendrik Smoels Avatar answered Nov 21 '25 02:11

Hendrik Smoels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!