NSOperation使用GCD,确保所有线程都在同一线程上 [英] NSOperation using GCD, ensure all on the same thread

查看:73
本文介绍了NSOperation使用GCD,确保所有线程都在同一线程上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个'concurrent'NSOperation,在它工作期间,它使用一些内部使用GCD的控制器类.当这些控制器类返回其完成块时,该完成块在另一个线程上.

I have a 'concurrent' NSOperation, and during it's work it uses some controller classes that internally use GCD. When these controller classes return with their completion block, the completion block is on another thread.

我知道我可以将当​​前线程存储在操作启动方法中并运行performSelectorOnThread:,但是理想情况下,我希望将完成内容包装在GCD块中,并分派到与操作开始时相同的线程上.使用GCD甚至可以做到这一点,因为我只能指定要分发的队列.

I know I could store the current thread in the operation start method and run performSelectorOnThread:, but ideally I would like to wrap the completion in a GCD block and dispatch onto the same thread as the operation started on. Is this even possible with GCD, as I can only specify a queue to dispatch to.

将这项工作恢复到操作开始所在的同一线程上的最佳方法是什么?除了我已经建议的以外,除非这是最好的方法.

What's the best way to bring this work back onto the same thread that the operation started on? Apart from what I already suggested... unless this is the best way.

推荐答案

我认为这真的不可能/不建议.从iOS 4开始,NSOperation使用GCD,并且随着GCD管理我的线程-我认为我不应该保留对它们的引用.

I don't think this is really possible/advisable. Since iOS 4 onwards, NSOperation is using GCD , and as GCD is managing my threads - I don't think I should be keeping references to them.

我确实找到了一些在特定线程上执行代码块的util方法.参见 Practical Blocks by Mike Ash 本文做类似的事情.

I did find some util methods for executing blocks of code on a particular thread. See Practical Blocks by Mike Ash or this article doing similar thing.

因为我的目标是将核心数据调用保持在同一线程上,所以我选择升级代码以使用具有NSPrivateQueueConcurrencyType的父/子托管对象上下文,然后在托管对象上下文上使用performBlock:以确保所有核心数据正确执行了各个线程上的回调.

As my goal was to keep my core data calls on the same thread, instead I opted to upgrade my code to use parent/child managed object contexts with NSPrivateQueueConcurrencyType, and then used performBlock: on the managed object context to ensure all my call backs on the separate threads got executed correctly by core data.

这篇关于NSOperation使用GCD,确保所有线程都在同一线程上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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