user4951
user4951

Reputation: 33080

Is this code managedobjectcontext guaranteed to be thread safe?

In my system, every thread has it's own managedObject Context.

Sometimes I want an equivalent object for a specific object.

So I make this category

-(NSManagedObject *) moVersionForThisThread
{
    NSManagedObjectID * moID = [self objectID];
    NSManagedObject * mo= [[BGMDCRManagedObjectContextThreadHandler managedObjectContext]existingObjectWithID:moID error:nil];
    return mo;
}

As far as I know, [self objectID] is save for all thread and existObjectWithID is also threadSafe. Right? We always get the right object right?

Nothing can go wrong?

Right?

Just making sure.

Upvotes: 1

Views: 101

Answers (1)

chasew
chasew

Reputation: 8828

I believe you have missed the boat on how objectIDs are thread safe. It is perfectly acceptable to use the objectID on a separate thread, but you need to retrieve that objectID from the managed object while on the thread where that object was instantiated. In other words, you will likely run into thread issues with your code [self objectID] if you are calling moVersionForThisThread on a thread other than the your object's original thread.

I would suggest plugging in this library into your project for debugging, which will give you warnings if you are accessing managed objects on the incorrect thread: https://github.com/GrahamDennis/GDCoreDataConcurrencyDebugging

Upvotes: 2

Related Questions