There are two ways to get nsurlconnection to run in a sub-thread, and to add nsurlconnection to run Loop or nsoperationqueue.
As mentioned earlier, you can manually add Nstimer to the Nsrunloop,cocoa library and also provide a way for others to manually join Nsrunloop, which have Nsport, Nsstream, Nsurlconnection, Nsnetservices, methods are [Scheduleinrunloop:formode:] forms. For the time being, I'll just introduce the most commonly used nsurlconnection class to see how to add nsurlconnection network downloads to the other thread's run loop.
If the nsurlconnection is started in the main thread, it is actually running in the main thread-not another thread that starts up, but with an asynchronous run feature, which is really the clever thing about the run loop. If you have a preliminary understanding and concept of the run loop, you can actually understand the operation of Nsurlconnection, which actually requires the current thread to have a run loop.
-(void) Scheduleinrunloop: (Nsrunloop *) Arunloop Formode: (NSString *) mode; Will be added to the specified run loop, it must be guaranteed that nsurlconnection cannot be started, otherwise it won't work.
-(void) Unschedulefromrunloop: (Nsrunloop *) Arunloop Formode: (NSString *) mode; Will cancel the run in the specified run loop and will actually stop nsurlconnection running
Here's how to run Nsurlconnection's main implementation code in other threads:
Nsrunloop *runloop; //global
[Selfperformselectorinbackground:@selector(thread) withobject:nil ]; //Start the thread that contains the run loop
nsurlconnection *conn = [[nsurlconnection alloc] initwithrequest: request delegate:self startimmediately:NO]; // Note that you cannot start Nsurlconnection first
[conn scheduleinrunloop:runloop formode:nsrunloopcommonmodes ]; //Specify to run Nsurlconnection in the thread started above
[conn start]; Start Nsurlconnection
-(void) thread
{
Runloop = [nsrunloop currentrunloop];//set to the current thread's run loop value
while (condition)
{
[Runloop rununtildate: [nsdate datewithtimeintervalsincenow:1.0]];//start run loop
}
}
Adding nsurlconnection to the nsoperationqueue is basically similar to the way it works:
Nsoperationqueue *queue = [[Nsoperationqueuealloc] init];
nsurlconnection *conn = [[nsurlconnection alloc] initwithrequest: request delegate: Self startimmediately:NO];
[Conn setdelegatequeue:queue];
[conn start];
Let Nsurlconnection run in a child thread