Networking using a separate thread on iOS
ios, multithreading, networking
Solution
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];
}
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.
All network callbacks will be called on NetworkThread, then processing your response data on NetworkThread, push final data to main thread, update UI.
Problem
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. 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? EDIT: 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.