NSInvocationOperation and main thread
Suppose I have a view with some UIKit object as its subview (for example UIActivityIndicatorView
- it doesn't matter). This view also has a selector called doSomething
, which manipulates the UIKit object in some way (in our example, it can start or stop displaying the indicator).
I am creating NSInvocationOperation
(from parts of the view code) using initWithTarget:self selector:@selector(doSomething) object:nil
. Then add it to NSOperationQueue
. And everything works fine.
How?! It should be a new thread and a non-thread safe UIKit object! Why was the error not found (and failed)?
a source to share
A class NSInvocationOperation
is a concrete subclass NSOperation
that implements a non-competitive operation .
In a non-concurrent operation, the operation is performed synchronously , that is, the operation object does not create a separate thread on which to perform the task. Thus, when a start
non-concurrent operation method is called , the operation is performed immediately on the current thread. By the time the method of start
such an object returns control to the caller, the task itself is complete.
However, usage NSOperationQueue
changes this behavior. NSOperationQueue always performs operations at the same time; a non-concurrent operation requires a separate thread to execute concurrently, and NSOperationQueue
this thread.
This means that if you execute NSInvocationOperation
yours directly, you will be able to access your UIKit object thread-safe (the operation will be done in a single thread). In your case, if you are using NSOperationQueue
, you should schedule work that uses the UIKit object on the main thread using NSObject performSelectorOnMainThread: withObject: waitUntilDone: from your call selector.
a source to share