Objective-C: Calling a C function on the Main Thread From a Background Thread

Share Button

Assume you have a variable that’s a C function pointer, and that function may directly or indirectly invoke some GUI code:

In a threaded environment, it would be unsafe to execute this function from a background thread. Objective-C’s NSObject has a selector performSelectorOnMainThread  that we can take advantage of, even though our C function isn’t a selector.  Simply create a wrapper object:

and when you need to execute the C function, create an instance, assign the function pointer, and execute the method that calls it:

Added bonus: for a much more general solution, see these two blog posts: Invoke any Method on any Thread and Performing any Selector on the Main Thread.