swift - 为什么我应该使用 NSManagedObjectContext 的 Perform() 和 PerformAndWait() 而我可以使用 DispatchQueue.global

标签 swift xcode core-data nsmanagedobjectcontext dispatch-queue

我对在后台队列上运行 CoreData 代码有一些困惑。

我们可以使用一些方法使用 NSManagedObjectContext 在后台线程上执行 CoreData 代码。

viewContext.perform { /*some code will run on the background thread*/ }
viewContext.performAndWait{ /*some code will run on the background thread*/ }

我的问题是为什么我应该使用这些函数,而不是使用普通方式使用 DispatchQueue 在后台线程上运行一些代码

DispatchQueue.global(qos: .background).async { 
     /*some code will run on the background thread*/ 
}

最佳答案

因为performperformAndWait是线程安全的。

假设您有两个上下文。

let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
let mainContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

通过使用performperformAndWait,您可以保证它们在创建的队列中执行。否则,您将遇到并发问题。

所以你可以得到下面的行为。

DispatchQueue.global(qos: .background).async {
        //some code will run on the background thread
        privateContext.perform {
            //some code will run on the private queue
            mainContext.perform {
                //some code will run on the main queue
            }
        }
    }

否则,它们都将在后台执行,如以下代码所示。

DispatchQueue.global(qos: .background).async {
        //some code will run on the background thread
            do {
                //some code will run on the background thread
                try privateContext.save()
                do {
                    //some code will run on the background thread
                    try mainContext.save()
                } catch {
                    return
                }
            } catch {
                return
            }
        }

要了解有关并发的更多信息,这里有 link Apple 文档。

关于swift - 为什么我应该使用 NSManagedObjectContext 的 Perform() 和 PerformAndWait() 而我可以使用 DispatchQueue.global,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807900/

相关文章:

swift - NSURLErrorDomain 代码 = -1002 尽管转义了受限字符

ios - 导航左栏按钮项目作为图像 Logo

ios - Collectionview 中显示多个 Parse.com 行图像?

iphone - Objective C NSCFString 与 NSMutableArrays 的泄漏

ios - Init View Controller 顶部和底部的额外空间

ios - UIImage 存储在 CoreData 到 UIWebView HTML Doc

ios - 尽管有 `if let` 构造,编译器告诉我解包变量

iOS Today 扩展无法构建

objective-c - XCode 4 是否支持区域以及您的代码管理方法是什么?

ios - CoreData & RestKit - 从多个来源获取相同的实体类型