简体   繁体   English

如何在NSOperation中实现异步网络调用

[英]How to implement asynchronous network calls in an NSOperation

I have an NSOperation derived class which performs asynchronous download. 我有一个NSOperation派生类,它执行异步下载。
Because the download operation has to be initiated from the main thread, the response is also completed on the main thread. 因为必须从主线程启动下载操作,所以响应也在主线程上完成。

Once the download has completed, I want to perform more heavy operations on the downloaded data within the NSOperation . 下载完成后,我想对NSOperation下载的数据执行更繁重的操作。

How do I get the operations after the download has completed to be performed in a background thread again within the existing NSOperation ? 下载完成后如何在现有NSOperation再次在后台线程中执行操作?

If you instead of moving to main thread in the NSOperation, rather start the connection in the current thread being run by your NSOperation. 如果您不是在NSOperation中移动到主线程,而是在NSOperation运行的当前线程中启动连接。

Then, keep the NSURLConnection alive by adding a NSPort to the NSRunLoop . 然后,通过向NSRunLoop添加NSPort来保持NSURLConnection活跃。
Now all the callbacks will be received in the same thread as the one you started the connection in - and you may continue to perform your additional work here, which is already in the background. 现在所有回调都将在与您启动连接的线程相同的线程中接收 - 您可以继续在此处执行其他工作,这已在后台。

NSOperation is simply a managed task. NSOperation只是一项托管任务。 You should use it for doing network calls outside of the main thread. 您应该使用它在主线程之外进行网络调用。

The subtlety in dealing with asynchronous code inside NSOperations lies in the NSOperation will complete and exit (and be disposed of from memory) before the callback returns. 在NSOperations中处理异步代码的微妙之处在于NSOperation将在回调返回之前完成并退出(并从内存中处理掉)。 The NSOperationQueue doesn't know or care that your code is asynchronous. NSOperationQueue不知道或不关心您的代码是异步的。

Using the existing runloop for the operation and explicitly setting complete on the NSOperation will keep the operation alive to recieve the callback and to mark itself complete. 使用现有的runloop进行操作并在NSOperation上显式设置完成将使操作保持活动状态以接收回调并标记自己完成。

When the async callback returns (before setting the operation to complete) the code inside the NSOperation should make a call to the main thread possibly by sending a block to update the UI. 当异步回调返回时(在设置操作完成之前),NSOperation内的代码应该通过发送一个块来更新UI来调用主线程。

Dont expect to keep the NSOperation around after it completes to do anything with it. 不要期望在它完成任何事情之后保持NSOperation。 Its a disposable task object which should not live after it completes. 它是一个一次性的任务对象,它完成后不应该存在。

As suggested by the existing answer, you should do as much of the processing in the NSOperation that does the network call itself. 正如现有答案所建议的那样,您应该在NSOperation中进行与网络调用本身一样多的处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM