First of all I am writing code for iphone. I need to be able to call a method on the main thread without using performSelectorOnMainThread
. The reason that I don't want to use performSelectorOnMainThread
is that it causes problem when I am trying to create a mock for unit testing.
[self performSelectorOnMainThread:@Selector(doSomething) withObject:nil];
The problem is that my mock knows how to call doSomething
but it doesn't know how to call performSelectorOnMainThread
.
So Any solution?
The main thread is created automatically when our program is started. To control it we must obtain a reference to it. This can be done by calling the method currentThread( ) which is present in Thread class. This method returns a reference to the thread on which it is called.
When an application is launched in Android, it creates the first thread of execution, known as the “main” thread. The main thread is responsible for dispatching events to the appropriate user interface widgets as well as communicating with components from the Android UI toolkit.
The main thread is the one that starts our program, and it's also the one where all our UI work must happen. However, there is also a main queue, and although sometimes we use the terms “main thread” and “main queue” interchangeably, they aren't quite the same thing.
currentThread(). getName()); where currentThread() is a static method of the Thread class, which refers to current thread in execution; and getName() is the function which gives the name of that thread.
Objective-C
dispatch_async(dispatch_get_main_queue(), ^{ [self doSomething]; });
Swift
DispatchQueue.main.async { self.doSomething() }
Legacy Swift
dispatch_async(dispatch_get_main_queue()) { self.doSomething() }
There's a saying in software that adding a layer of indirection will fix almost anything.
Have the doSomething method be an indirection shell that only does a performSelectorOnMainThread to call the really_doSomething method to do the actual Something work. Or, if you don't want to change your doSomething method, have the mock test unit call a doSomething_redirect_shell method to do something similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With