Assume you have a variable that’s a C function pointer, and that function may directly or indirectly invoke some GUI code:
1 2 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@interface TestObject : NSObject { MyFunc func; } @property MyFunc func; - (void)invoke; @end @implementation TestObject @synthesize func; -(void)invoke { if (func) func(); } @end |
and when you need to execute the C function, create an instance, assign the function pointer, and execute the method that calls it:
1 2 3 4 5 |
TestObject *testObject = [[TestObject alloc] init]; testObject.func = func; [testObject performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:YES]; |
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.