平常在项目中没有使用过 Core Data, 因为我觉得它的学习曲线还挺陡峭,整个框架给人的感觉很复杂和笨重,因此一直没有使用它。但是看到喵神这份上级向的十个 iOS 开发面试题中和这份百度面试题中都有涉及到 Core Data 的内容,我想还是有必要好好研究一下它,毕竟它是 Apple 官方的持久化方案,我们可以取其精华,弃其糟粕,另一方面未来我们也可能因为各种原因接手或参与使用 Core Data 的项目。
这篇文章主要想探讨上面提到的面试题中的两个关于 Core Data 的问题:
- 你实现过多线程的Core Data么?NSPersistentStoreCoordinator,NSManagedObjectContext和NSManagedObject中的哪些需要在线程中创建或者传递?你是用什么样的策略来实现的?
- Core Data:中多线程中处理大量数据同步时的操作。
在回答这两个问题之前,我们先看 Apple 是怎么告诉我们使用多线程的 Core Data 的,在最新的(2017-03-27) Core Data Programming Guide 中有一节 Concurrency with Core Data,它没有直接说如何使用多线程,只是说了 managed object context 在多线程中的两种使用模式:
In Core Data, the managed object context can be used with two concurrency patterns, defined by NSMainQueueConcurrencyType and NSPrivateQueueConcurrencyType.
NSMainQueueConcurrencyType is specifically for use with your application interface and can only be used on the main queue of an application.
The NSPrivateQueueConcurrencyType configuration creates its own queue upon initialization and can be used only on that queue. Because the queue is private and internal to the NSManagedObjectContext instance, it can only be accessed through the performBlock: and the performBlockAndWait: methods.
对于多线程中对象的传递则有这么一段描述: