在Core Data中使用多线程一般不是为了能够提高性能和效率,而是为了使主线程能够不被阻塞,使能够在做其他数据操作的时候,UI还能够继续响应用户的行为。当执行fetch操作时,Core Data系统会根据需要自动开启多个线程做相应的操作,因此我们自己添加多线程并不能提高效率,而仅仅是为了能够将主线程丛繁重的数据操作中解脱出来。
苹果官方文档中对Core Data并发操作的说明:
Concurrency with Core Data:
1、Use Thread Confinement to Support Concurrency.
2、Track changes in Other Threads Using Notifications
3、Fetch in the Background for UI Responsiveness
4、Saving in a Background Thread is Error-prone
5、If You Don‘t Use Thread Confinement
There are serveral situations in which performing operations with Core Data on a background thread or queue is beneficial, in particular if you want to ensure that your application‘s user interface remains responsive while Core Data is undertaking a long-running task. If you do perform concurrent operations with Core Data, however, you need to take considerable care that object graphs do not get into an inconsistent(不一致) state.
If you choose to use concurrency with Core Data, you also need to consider the application environment. For the most part, AppKit and UIKit are not thread safe; in particular, on OS X Cocoa bindings and controllers are not thread safe - if you are using these technologies, multi-threading may be complex.