Nate Potter
Nate Potter

Reputation: 3222

Deleting an NSManagedObject in the Main Thread from an NSOperation

When invoking deleteObject: on an NSManagedObjectContext on the main thread from an NSOperation, do I also need to reference the objectID on the main thread? Currently I am deleting an NSManagedObject in the main thread from an NSOperation in the following way...

NSManagedObjectContext *mainContext = [[[UIApplication sharedApplication] delegate] managedObjectContext];

- (void)deleteObject:(NSManagedObjectID *)objectID
 {
     // Delete on main context on the main thread
     [mainContext performSelectorOnMainThread:@selector(deleteObject:)
                              withObject:[mainContext objectWithID:objectID]
                           waitUntilDone:YES];
 }

It's working but I want to make sure it doesn't blow up on me later. The thing I'm not sure about is if [mainContext objectWithID:objectID] is referencing the NSManagedObjectContext from the NSOperation, or since that method invokation is within the performSelectorOnMainThread:withObject:waitUntilDone: is it all being performed on the main thread?

Upvotes: 0

Views: 1202

Answers (1)

ImHuntingWabbits
ImHuntingWabbits

Reputation: 3827

Instances of NSManagedObjectID are safe to share across thread boundaries. However your call to mainContext objectWithID: will get the actual object, which is not thread safe.

What you should probably do is wrap this in a selector or block which can be performed on the main queue.

dispatch_async(dispatch_get_main_queue(), ^{
    NSManagedObjectContext *mainContext = [[[UIApplication sharedApplication] delegate] managedObjectContext];
    NSManagedObject *obj = [mainContext objectWithID:objectID];
    if (obj) {
        [mainContext deleteObject:obj];
    }
})

Alternatively you can have your main thread queue do this for you:

[mainContext performBlock:^{
    NSManagedObject *obj = [mainContext objectWithID:objectID];
    if (obj) {
        [mainContext deleteObject:obj];
    }
}]

Of course, all of this begs the question, why are you trying to delete objects in a main-thread based context from an instance of NSOperation on another thread?

Upvotes: 2

Related Questions