在iOS上使用单独的线程进行联网 [英] Networking using a separate thread on iOS

查看:81
本文介绍了在iOS上使用单独的线程进行联网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发的应用程序是一个与OS X服务器通信的iOS客户端.该应用程序的当前版本可完成主线程上的所有联网逻辑,并且可以很好地满足我的需求.

The application that I develop is an iOS client that communicates with an OS X server. The current version of this application does all the networking logic on the main thread and this works fine for what I want to do.

但是,在下一版本中,我希望网络逻辑更加灵活.为此,我想为其分配一个单独的线程,但是我不确定哪种解决方案适合我的需求.

However, in the next version, I want the networking logic be more flexible. For this to work, I would like to dedicate a separate thread to it, but I am not quite sure what solution is right for my needs.

起初,GCD看起来不错,但是似乎只适合在单独的线程上执行的工作块.我想做的是将所有网络逻辑放在单独的线程上. iOS客户端和OS X服务器之间的连接是持久的,所有数据流和处理应在该单独的线程上进行.

At first, GCD looked like a good candidate, but it seems to only be suitable for chunks of work to be executed on a separate thread. What I would like to do is have all the networking logic on a separate thread. The connection between the iOS client and the OS X server is persistent and all the data streaming and processing should occur on that separate thread.

问题归结为,哪种方法最适合这种情况?

The question boils down to, what approach is most suitable for this scenario?

为了摆脱任何混乱,我使用的连接利用了套接字和NSStream实例.我没有处理连接到远程Web服务器的问题.换句话说,AFNetworking和ASIHttpRequest对我来说不是一个选择.

To get rid of any confusion, the connection that I use makes use of sockets and NSStream instances. I am not dealing with connecting to a remote web server. In other words, AFNetworking and ASIHttpRequest are not an option for me.

推荐答案

  1. 您可以使用运行以下代码的runloop(我们称为NetworkThread)创建线程:

  1. You can create a thread with runloop(we call it NetworkThread), running following code:

while (!self.isCancelled) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    [pool release];
}

  • 然后您可以使用- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait在NetworkThread上执行网络请求选择器.

  • then you can use - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait to perform your network request selector on NetworkThread.

    所有网络回调将在NetworkThread上调用,然后在NetworkThread上处理响应数据,将最终数据推送到主线程,更新UI.

    All network callbacks will be called on NetworkThread, then processing your response data on NetworkThread, push final data to main thread, update UI.

    这篇关于在iOS上使用单独的线程进行联网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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