CoreData  执行executefetchrequest卡死解决办法

本文介绍了在CoreData执行fetch请求时导致UI卡死的问题及解决办法。通过苹果官方文档了解到,当在后台线程执行fetch请求时,CoreData会自动优化,但跨线程使用NSManagedObjectContext会导致问题。解决策略是在每个线程中创建独立的NSManagedObjectContext实例,关联到同一个NSPersistentStoreCoordinator,以确保线程安全和UI响应性。


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

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

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

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

nsmanagedobjectcontext that was created with a queue

翻英文资料查看。


http://stackoverflow.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内的执行。


评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值