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

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

typedef void (*MyFunc)(void);
MyFunc func = ...

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:

@interface TestObject : NSObject {
    MyFunc func;
@property MyFunc func;
- (void)invoke;

@implementation TestObject
@synthesize func;
-(void)invoke {
    if (func)

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

TestObject *testObject = [[TestObject alloc] init];
testObject.func = func;
[testObject performSelectorOnMainThread:@selector(invoke)

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.