Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro to run method on main thread

I want an easy way to drop code in the beginning of a method that will force the method to only be run on the main thread (because the method updates UI elements).

Currently, I have something like:

 if (![NSThread isMainThread]){
    [self performSelectorOnMainThread:_cmd withObject:_results waitUntilDone:NO];
    return;
}

but I want a way to include this in a macro without me having to enter the arguments for the method. It seems like there should be some way to iterate over the list of parameters passed to the current method and create an NSInvocation or similar. Any thoughts?

like image 975
Adam Shiemke Avatar asked Dec 20 '22 20:12

Adam Shiemke


1 Answers

Will this work?

#define dispatch_main($block) (dispatch_get_current_queue() == dispatch_get_main_queue() ? $block() : dispatch_sync(dispatch_get_main_queue(), $block))

This will also work if you call it from the main thread too, a bonus. If you need asynchronous calling, just use dispatch_async instead of dispatch_sync.

like image 117
Richard J. Ross III Avatar answered Jan 15 '23 12:01

Richard J. Ross III