Are asynchronous NSURLConnections multithreaded

I noticed that if I create an NSURLConnection and run the query, everything will be fine. My delegate methods are called, and the last delegate method is called well after the code that invokes the connection has completed. Excellent.

This makes me think that connections are asynchronous, which implies that they are multithreaded. It's right? Can they be asynchronous, but in the same thread? No, this is crazy - right?

But in every example I saw with NSOperation, NSURLConnections are always scheduled by InRunLoop, after which [runLoop runMode ...] is called in a while loop.

Can someone explain what is going on here? It seems to me that the first case requires spawning of secondary threads, but there is no manual call of the execution loop (in these threads), while NSOperation (in the new thread) requires manual calling of the execution loop.

Why in the first case does not require a manual call?

+4
source share
3 answers

NSURLConnection creates a single background thread to manage all instances of itself, but this is usually not related to the caller, as delegate calls are made on any thread that owns the runloop on which the connection was scheduled. (This fact has turned to be very relevant for me lately, but these things really only happen when working with crazy crashers in multi-threaded applications.)

For more information about the caller, you should see the documents for -[NSURLConnection scheduleInRunLoop:forMode:] . It explains how to manually handle scheduling and unplanned and how NSURLConnections behaves in a multi-threaded environment.

If you do not know how run loops work and how they perform asynchronous actions without requiring additional threads, you should read the Run Loops in the Threading Programming Guide. This is a very important topic for moving to a more advanced Cocoa development.

+4
source

Because the main thread already has a run loop, I would suggest.

0
source

If you want to start NSURLConnection in another thread, you must create a start loop like this in the main thread method:

 while (!finished) { [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]]; } 
0
source

Source: https://habr.com/ru/post/1342198/


All Articles