Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method on the main thread?

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?

like image 705
aryaxt Avatar asked Apr 09 '11 16:04

aryaxt


People also ask

How to reference the main thread Java?

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.

What is main thread?

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.

What is the main thread in IOS?

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.

How to get the name of the main thread?

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.


2 Answers

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() } 
like image 115
aryaxt Avatar answered Sep 29 '22 16:09

aryaxt


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.

like image 26
hotpaw2 Avatar answered Sep 29 '22 15:09

hotpaw2