Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatch_get_current_queue() deprecated, is there an alternative for safe CoreData?

Many people have asked a question with similar title, but very different purpose:

CoreData requires that you keep track of your current queue, your current thread, and your current NSOperationQueue (if you're an NSOperation), if you allow method calls to come from other classes (which, by default, every class allows). There are no "maybes" about this: it's a hard requirement.

That's fine, and in general it's easy to ensure:

NSAssert( [NSThread currentThread].isMainThread || myPrivateQueue == dispatch_get_current_queue(), @"You tried to call this method from an external thread, or a queue other than my internal private queue. That's not legal, and will cause data corruption" );

...except that Apple has gone and deprecated dispatch_get_current_queue(), apparently "because people were abusing it to get around missing functionality in GCD / bits of GCD they didn't understand".

NB: my usage of dispatch_get_current_queue() above appears to be correct and non-abusive, judging by Apple's header comment: the whole point is that I'm checking that the queue is the private one I created (which Apple claims is acceptable usage).

Leaving aside the wisdom of deprecating something simply because of flaws in its implementation :( ... has anyone found a workaround for this being removed by Apple. Specifically: with CoreData, you have to track the queue - is there another way of doing that?

(this matters because: with CoreData, if you allow something to accidentally call such a method, you won't get a "crash", you'll get "data corruptioin that will show up at some point in the future when it's too late to fix it")

like image 615
Adam Avatar asked Aug 29 '13 12:08

Adam


1 Answers

performBlock always run it in correct thread. Just use:

[yourManagedObjectContext performBlock:^{
//do your stuff here
}];

You don't need track current context anymore, because your MOC knows which thread fire this MOC in first place. When you use performBlock or performBlockAndWait you are safe.

like image 112
Jakub Avatar answered Oct 03 '22 11:10

Jakub