[Reading Notes] iOS network-asynchronous request and running cycle, Reading Notes ios
Asynchronous requests need to run a loop. When data is transmitted to the server or received by the client, the running cycle is used to implement communication between events and delegate objects. When an asynchronous request is sent, it will operate on the running cycle of the current thread. The implementation details are very important, because there is no running loop in the GCD block or the thread created through NSOperationQueue. Therefore, if an asynchronous request is sent on the background thread, You need to determine whether the thread has a running loop or uses another running loop. The following code snippet shows how to explicitly specify request processing to a running loop.
NSURLConnection connection = [[NSURLConnection alloc] initWithRequest: request delegate: self startImmediately: NO]; [connection scheduleInRunLoop: [nsunloop mainRunLoop] forMode: NSDefaultRunLoopMode]; [connection start]
In the first operation, the NSURLConnection object is created, but the method is not started immediately, so that further initialization can be performed. The next code gets the running cycle of the main thread, and then provides it to the connection as its running cycle. Finally, the connection starts to be processed through the start method. If you do not want to execute asynchronous requests in the main running loop, you need to create a running loop on another thread and then schedule the connection for the newly created running loop.
Reference: iOS network advanced programming-enterprise application development for iPhone and iPad