CoreData 执行executefetchrequest卡死解决办法

时间:2023-03-09 16:31:12
CoreData  执行executefetchrequest卡死解决办法

在大量使用GCD和block以后发现程序会卡死在executefetchrequest执行。

反复测试无果。添加锁也无效。想来想去没发现问题。

容忍了就当人品问题。2天以后实在忍无可忍。

替换performBlock执行块得到如下错误

nsmanagedobjectcontext that was created with a queue

翻英文资料查看。

http://*.com/questions/4800889/what-does-apple-mean-when-they-say-that-a-nsmanagedobjectcontext-is-owned-by-the

苹果官方文档资料

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdConcurrency.html#//apple_ref/doc/uid/TP40003385-SW1

看到如下一句话

Fetch in the Background for UI Responsiveness

The executeFetchRequest:error: method intrinsically scales its behavior appropriately for the hardware and work load. If necessary, the Core Data will create additional private threads to optimize fetching performance. You will not improve absolute fetching speed by creating background threads for the purpose. It may still be appropriate, however, to fetch in a background thread or queue to prevent your application’s user interface from blocking. This means that if a fetch is complicated or returns a large amount of data, you can return control to the user and display results as they arrive.

Following the thread confinement pattern, you use two managed object contexts associated with a single persistent store coordinator. You fetch in one managed object context on a background thread, and pass the object IDs of the fetched objects to another thread. In the second thread (typically the application's main thread, so that you can then display the results), you use the second context to fault in objects with those object IDs (you use objectWithID: to instantiate the object). (This technique is only useful if you are using an SQLite store, since data from binary and XML stores is read into memory immediately on open.)

明白了原来在线程中NSManagedObjectContext会创建一些私有方法。跨线程使用时候就会出问题。

解决办法就是多个线程执行时候创建多个NSManagedObjectContext管理。关联到NSPersistentStoreCoordinator

同理解决

GCD

NSOperation内的执行。