difference between Runloop and thread? - objective-c

What is run loops actually ?
what a difference from thread ?
Where we must need to use run loop and where aren't we use ?

RunLoop is a looping mechanism. It is a kind of infinite loop.
Thread is a conceptual model of code execution(thread). Not directly related with loops or function calls. It denote flow of code. Internally, each thread has separate stack frame.
There exists the main thread (one and only one). By default, the main thread execute the main runloop.
The main runloop primarily handles keyboard and mouse input. Waiting infinitely for input events and calls appropriate event handlers.
One can create another thread and another runloop for background processing of not UI related events such as async socket, etc.

Related

If performSelectorOnMainThread:waitUntilDone: is called from the main thread, when will it execute?

I'm programming an application that makes use of asynchronous web requests using NSURLConnection, so I have multiple threads running. To ensure that the main logic of my app happens on one thread, I am making heavy use of performSelectorOnMainThread:waitUntilDone:. Sometimes though, I am running this on the main thread, which piqued my curiosity.
If performSelectorOnMainThread:waitUntilDone: is called while in the main thread? Does it act the same as just performSelector:? What if waitUntilDone: is YES? What if it is NO?
EDIT: I have found that when waitUntilDone: is YES, the selector is executed (almost) immediately, but I cannot figure out when it is executed if waitUntilDone: is NO.
performSelectorOnMainThread:withObject:waitUntilDone:
is a method to deliver message on main thread of your application. Here boolean value in parameter waitUntilDone: specifies that whether you want to block your main thread to execute specified selector or not.
for example -
if you written these two lines-
[self performSelectorOnMainThread:#selector(print) withObject:nil waitUntilDone:YES];
NSLog(#"Hello iPhone");
and this is the print method -
- (void) print
{
NSLog(#"Hello World");
}
then you will get this o/p
Hello World
Hello iPhone
so it first pause the execution of your main thread and print "Hello World" and then execute main thread again and print "Hello iPhone" because you specified YES in waitUntilDone:
but if you specified NO in waitUntilDone: then it will print like this -
Hello iPhone
Hello World
it clearly indicates that it put your request of executing the specified selector in a queue and as OS gets its main thread free it executed you request.
Calling performSelectorOnMainThread:withObject:waitUntilDone: either from main thread or a secondary thread doesn't make any difference in it's execution, it depends on what you specified in waitUntilDone:
for more info -
NSObject Class Reference
If the current thread is also the main thread, and you pass YES,
the message is performed immediately, otherwise the perform is
queued to run the next time through the run loop.
If YES, it can be performed before performSelectorOnMainThread:withObject:waitUntilDone: returns.
I have found that when waitUntilDone: is YES, the selector is executed (almost) immediately, but I cannot figure out when it is executed if waitUntilDone: is NO.
The bit about the run loop: Your main thread has a run loop. This more or less prevents a thread from exiting. A run loop manages a todo list. When its work is complete, it suspends execution of that thread for some time. Then it wakes up later and sees if has work to do.
The amount of work can vary greatly (e.g. it may do some really heavy drawing or file i/o between the time it awakes and the point your selector is performed. Therefore, it's not a good tool for really precise timing, but it should be enough to know how it works and how the implementations adds the work to the run loop.
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html
If waitUntilDone: is YES it acts as an immediate function call.
If waitUntilDone: is NO then it queues the call along with all other threads' calls.
This method queues the message on the run loop of the main thread
using the common run loop modes—that is, the modes associated with the
NSRunLoopCommonModes constant. As part of its normal run loop
processing, the main thread dequeues the message (assuming it is
running in one of the common run loop modes) and invokes the desired
method.
As noted above, things like drawing and I/O are prioritized over anything in queues. Once the main thread gets around to having time for queue service in the next event loop, there's a couple other details that make it not quite as simple as counting on first in first out:
1) dispatch_async() blocks ignore modes.
2) The performSelector variants with a specific mode argument -- event tracking, say -- may take precedence over ones with the default common modes argument in a loop running in that specific mode.
As a general rule, if you want predictable timing behaviours you should use the low level GCD dispatch functions that don't take account of higher level considerations like run loop modes.

Is it safe to set NetworkActivityIndicatorVisible value in secondary thread?

I wonder if AppDelegate is thread safe? I currently have an operation running networking tasks on the secondary thread, when the task begins, I would like to set NetworkActivityIndicatorVisible to YES, and when the task is done, set it to NO. Do I have to always call it in the main thread, or I can do it in the current run loop thread?
Thanks
In general, UIKit is not thread safe. While you may be able to "get away" with some things, you should always do UIKit stuff on the main thread. There are a few, well documented, exceptions.
The pattern for doing this from a background thread is simple.
dispatch_async(dispatch_get_main_queue(), ^{
// Put any code you want to execute in the main thread here.
});
The code inside the block you pass to dispatch_async will be scheduled to run in the main run loop.

Will performSelectorOnMainThread interrupt current code block?

If I have a background thread doing some network stuff, and some of the background methods make 'performSelectorOnMainThread' calls, will/can these calls interrupt execution of the current code block (which is being executed on the main thread)?
No, they will and can not. The performSelector group of methods schedule actions on the run loop. Only after your current code block returns to the run loop, these actions will be performed. (Assuming with "the current code block" you mean your code running on the main thread)
If waitUntilDone is set to YES, then absolutely it will definitely interrupt execution of the code calling performSelectorOnMainThread. If it's set to NO then it will queue the selector to be performed on the main thread.
If the caller of performSelectorOnMainThread is not the main thread, then whether or not the selector gets run before your "current code block" finishes will depend entirely upon the state the CPU is in. There might be more than one CPU so you might have 2 of your threads scheduled at the same time, or just the OS might have decided to schedule the main thread instead of your current thread after some time.
So basically, yes, these calls can interrupt execution of the current code block, just in the same way as you should be familiar with from multi-threaded programming.
[By "current code block" I am assuming you mean the caller of performSelectorOnMainThread]
Update:
Ah, right, you mean "Can it interrupt the code which is currently being executed on the main thread?". The answer to that, is definitely not. It is scheduled on the main thread's run loop to run next time round the loop.

NSTimer versus separate thread - which one to choose?

Let's assume we have simple UI and for whatever reason, every 5 seconds a UILabel needs to be updated.
I can now either setup an NSTimer which does the job, or create a separate thread which runs endlessly, sleeps 5 seconds, does its thing, sleeps again and so on.
Which one would I choose to go for? What are the differences?
You have to do UI operations on the main thread anyway, so unless your doing some processing prior to setting the label there would be no benefit of using another thread.
The UI can only be updated on the main thread of any program. If you want to do calculations for the label in a separate thread, that's perfectly fine, but the code to update your UI will have to operate on the main thread (or, you can use performSelectorOnMainThread:withObject:waitUntilDone: to call setText: on your label and have it operate correctly).
Use NSTimer.
Why?
As soon as you introduce extra threads, you introduce the possibility of a whole new class of bugs i.e. thread synchronisation issues. These tend to be very hard to diagnose and resolve due to their indeterminate nature.
You have to do UI updates on the main thread anyway. So your thread would have to do -performSelectorOnMainThread:withObject:waitUntilDone: to update the UI.
If the calculations for the label take a while (don't just assume they do, try it the simple way first and see), have your timer kick off an NSOperation to do the calculations and then have the NSOperations call -performSelectorOnMainThread:withObject:waitUntilDone: when it has finished.

Difference between performSelectorInBackground and NSOperation Subclass

I have created one testing app for running deep counter loop. I run the loop function in background thread using performSelectorInBackground and also NSOperation subclass separately.
I am also using performSelectorOnMainThread to notify main thread within backgroundthread method and [NSNotificationCenter defaultCenter] postNotificationName within NSOperation subclass to notify main thread for updating UI.
Initially both the implementation giving me same result and i am able to update UI without having any problem. The only difference I found is the Thread count between two implementations.
The performSelectorInBackground implementation created one thread and got terminated after loop finished and my app thread count again goes to 1.
The NSOperation subclass implementation created two new threads and keep exists in the application and i can see 3 threads after loop got finished in main() function.
So, my question is why two threads created by NSOperation and why it didn't get terminated just like the first background thread implementation?
I am little bit confuse and unable to decide which implementation is best in-terms of performance and memory management.
It's likely the operation queue is keeping threads alive, waiting for new operations to appear.
You have to remember that the operation queue is designed to work efficiently with many operations, so creating and destroying threads for each operation is going to hurt performance. So what you are seeing is probably just the way the queue is designed to work by keeping a pool of threads alive.
Basically, as long as you are using the operation queue properly and according to the documentation I wouldn't worry about it.