iphone - performBlock 在哪个线程上运行?

标签 iphone objective-c cocoa-touch core-data

确实是一个简单的问题,我的核心数据 UIManagedDocument 是在主线程上创建的,我想知道的是当我调用 performBlock 时是否在主线程(创建托管文档的同一线程)上阻塞队列/运行?

dispatch_queue_t backgroundQueue = dispatch_queue_create("DownloadQueue", NULL);
dispatch_async(backgroundQueue, ^{
    // Get data from web
    [document.managedObjectContext performBlock:^{
        // Add data to Core Data
    }];
});

最佳答案

您可以阅读苹果发行说明:CoreData Release Notes for iOS5

You can use contexts using the confinement pattern just as you have prior to OS X v10.7 and iOS 5. You send the contexts messages directly; it’s up to you to ensure that you send the messages from the right queue.

You use contexts using the queue-based concurrency types in conjunction with two new methods: performBlock: and performBlockAndWait:. You group “standard” messages to send to the context (including initialization such as setting the persistent store coordinator and so on) within a block to pass to one of these methods. The one exception is: if your code is executing on the main thread, you can invoke methods on the main queue style contexts directly instead of using the block based API.

performBlock: and performBlockAndWait: ensure the block operations are executed on the queue specified for the context. The performBlock: method returns immediately and the context executes the block methods on its own thread. With the performBlockAndWait: method, the context still executes the block methods on its own thread, but the method doesn’t return until the block is executed.

It’s important to appreciate that blocks are executed as a distinct body of work. As soon as your block ends, anyone else can enqueue another block, undo changes, reset the context, and so on. Thus blocks may be quite large, and typically end by invoking save:.

关于iphone - performBlock 在哪个线程上运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12735213/

相关文章:

ios - 如何在 iOS 上播放电影

iOS - viewDidUnload 奇怪的调用

iphone - iPhone 中的 Http 请求/响应 API

objective-c - "Subclass"核心数据模型

iphone - 如何在核心动画中强制执行特定的旋转方向(即顺时针)?

iphone - 在每个单元格中包含 UI 元素的 UITableView 中缓慢滚动

ios - 尝试替换NSString中的字符串的许多实例时,内存使用过多

iphone - 如何关闭 UIWebView 上的键盘?

iphone - MapQuest ios API无法请求路线

iphone - 如何使用SSH使用Internet特权/远程服务器的访问权限