CoreData与GCD队列的AFNetworking请求不兼容吗? [英] CoreData not compatible with an AFNetworking request from a GCD queue?

查看:62
本文介绍了CoreData与GCD队列的AFNetworking请求不兼容吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GCD启动一个长时间运行的后台进程('run_loop'),该进程创建一个NSManagedObjectContext('MOC'),监视CoreData对象,有时(当它们准备就绪时)将它们的序列化上载到网络服务器,然后将其删除。

I am using GCD to start a long-running background process ('run_loop') that creates an NSManagedObjectContext ('MOC'), monitors CoreData objects, and sometimes (when they're ready) uploads a serialization of them to a webserver and then deletes them.

我正在使用AFNetworking进行HTTP调用。问题出在请求完成处理程序块中,因为这些块在与MOC所有者不同的线程中运行,而CoreData不支持该线程。

I am using AFNetworking for the HTTP calls. The problem is in the request completion handler blocks, as the blocks run in a different thread to the owner of the MOC, which isn't supported by CoreData.

我有尝试从GCD run_loop块的开头存储NSThread,并使用performSelector:onThread:run_thread,但这似乎根本没有真正调用选择器。

I have tried storing the NSThread from the start of the GCD run_loop block, and using performSelector:onThread:run_thread but this just doesn't seem to actually call the selector at all.

我尝试使用dispatch_sync(run_queue),但这不能保证线程是相同的,只能保证GCD队列。

I have tried using dispatch_sync(run_queue) but this doesn't guarantee the thread is the same, only the GCD queue. A different MOC save in the main thread later hangs.

最后,唯一起作用的方法是在完成回调处理程序中设置布尔值,并引入额外的逻辑来检测布尔开关并从主要run_loop执行MOC工作。

Eventually the only thing that worked was to set a boolean in the completion callback handler, and to introduce extra logic to detect the boolean switch and to perform the MOC work from the main run_loop.

有人能提出更优雅的解决方案吗?还是CoreData根本与从GCD队列开始的AFNetworking请求不兼容,我应该从头开始看一下较低级别的线程控制?

Would anyone be able to suggest a more elegant fix? Or is CoreData simply not compatible with an AFNetworking request started from a GCD queue, and I should look at a lower-level thread control from the start?

推荐答案

Hmm ..处理MOC和线程的推荐方法是始终制作一个新的MOC,该MOC是主线程的MOC的子MOC。让主线程完成所有保存工作,但您的GCD线程基本上可以将更改合并到主MOC中。

Hmm .. the recommended way to deal with MOC and threads is to always make a new MOC that is a sub-moc of your main thread's MOC. Let the main thread do all the saving, but your GCD threads can basically merge changes to the main MOC.

使用 https://github.com/magicalpanda/MagicalRecord/ 以便以更简单的方式实现此目的。

I've had pretty good success working with https://github.com/magicalpanda/MagicalRecord/ to facilitate this in a simpler fashion.

这篇关于CoreData与GCD队列的AFNetworking请求不兼容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆