Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to detect if code is running on the main thread in Objective-C? (iOS) [duplicate]

My code needs to guarantee a certain operation run on the main thread, but calls may come from background threads.

To detect situations in the background I was using the following:

- (void)selectorToRunInMainThread:(id)arguments {     // push to main thread         if ([NSRunLoop currentRunLoop] != [NSRunLoop mainRunLoop])         {             [self performSelectorOnMainThread:@selector(selectorToRunInMainThread:) withObject:arguments waitUntilDone:NO];             return;         }      /*     ... function content ...     */ } 

This works on iOS 4 and iOS 3.2 but not on iOS 3.1.3 and earlier. In these earlier versions, the function will keep getting called in an endless loop.

Changing the comparison to:

if (![[NSRunLoop currentRunLoop] isEqualTo:[NSRunLoop mainRunLoop]])

has no effect, they still never compare to the same value.

I found a solution that appears to be working, but I'd like to see what other people suggest first.

like image 906
Cameron Hotchkies Avatar asked Nov 19 '10 23:11

Cameron Hotchkies


People also ask

How we can ensure execute code in the main thread?

If you're on a background thread and want to execute code on the main thread, you need to call async() again. This time, however, you do it on DispatchQueue. main , which is the main thread, rather than one of the global quality of service queues.

What is main thread in IOS Swift?

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.


1 Answers

[NSThread isMainThread] and, if not, dispatch via any of a number of mechanisms to the main thread (what you have is fine).

like image 110
bbum Avatar answered Oct 11 '22 16:10

bbum