不推荐使用dispatch_get_current_queue(),是否有安全CoreData的替代方案?

Ada*_*dam 6 core-data grand-central-dispatch ios

许多人提出了一个类似标题的问题,但目的却截然不同:

如果允许方法调用来自其他类(默认情况下,每个类允许),CoreData 要求您跟踪当前队列,当前线程和当前NSOperationQueue(如果您是NSOperation).对此没有"可能":这是一个很难的要求.

这没关系,一般来说很容易确保:

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" );
Run Code Online (Sandbox Code Playgroud)

...除了苹果公司已经废弃了dispatch_get_current_queue(),显然是"因为人们滥用它来解决他们不理解的GCD/GCD位中缺少的功能".

注意:我对上面的dispatch_get_current_queue()的使用似乎是正确的和非滥用的,从Apple的标题评论判断:整点是我正在检查队列是我创建的私有队列(Apple声称这是可接受的用法) .

暂且不谈贬低某些东西的智慧仅仅是因为它的实现存在缺陷:(有没有人找到了解决方法,因为Apple将其删除.具体来说:使用CoreData,你必须跟踪队列 - 是否有另一种方法可以做到这一点?

(这很重要,因为:使用CoreData,如果你允许某些东西意外地调用这种方法,你就不会得到"崩溃",你会得到"数据腐败,这将在未来的某个时刻出现,因为它为时已晚要解决这个问题")

Jak*_*kub 4

performBlock始终在正确的线程中运行它。只需使用:

[yourManagedObjectContext performBlock:^{
//do your stuff here
}];
Run Code Online (Sandbox Code Playgroud)

您不再需要跟踪当前上下文,因为您的 MOC 知道哪个线程首先触发该 MOC。当你使用performBlock或者performBlockAndWait你是安全的。