How can I determine if code is running in the main thread in Objective-C? (IOS)

My code should ensure that a specific operation is performed on the main thread, but calls may arise from background threads.

To detect situations in the background, I used 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 continue to receive calls in an infinite loop.

Comparison Change:

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

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

I found a solution that seems to work, but I would like to see what other people offer.

+42
multithreading ios objective-c iphone
Nov 19 '10 at 23:55
source share
1 answer

[NSThread isMainThread] and, if not, send it through any of several mechanisms to the main thread (which is okay with you).

+88
Nov 20 2018-10-10T00:
source share



All Articles