Understanding Multithreading in iOS
-
08-07-2021 - |
Question
I am trying to understand multi-threading on iOS in more detail. I went through some of the class references like NSThread
, NSRunLoop
, NSTask
..
First of all as indicated on the following link: use of runloop
Runloop
runs within a Thread
.
So why do we need to define our own Runloop
in our app? In the case of NSThread
it is useful because some of time-consuming processes can run in a separate thread so that the app will still be responsive on the main thread.
La solution
Interacting with the thread's run loop may be useful if you have a thread whose work you want to continue periodically. That is, a run loop would do some work, and then when it is finished with that work, it would put the thread to rest for some time, then resume work at a later time -- effectively preventing the thread from exiting. You won't need to interact with them or configure/create them yourself regularly (only a small percentage of apps would qualify, if you are using high level abstractions such as Foundation because Foundation would set them up on your behalf in most scenarios).
If your secondary thread just does a specified task and does not need to wait for some external event (e.g. a download to finish), you would (typically) not need to interact with the run loop.
Autres conseils
You might consider looking at using NSOperationQueues
, NSOperations
and NSBlockOperations
instead as these will manage themselves, will allow for cancellation of tasks and can be scheduled on main and background threads.