objective-cmacoscocoansevent

How to run custom code in the main thread of Cocoa applications


I'm a windows developer and I'm having a hard time understanding the right way to run code in the NSApplication's main thread.

Most of my code is running in a cvdisplaylink thread (it's an opengl app) THe problem is that I can't call things like NSOpenPanel from it - it crashes the app and warns about only running stuff like this from the main thread.

It's fine, but the main thread is completely opaque as far as I understand, and I can only make it do things with events. The NSApp sendAction method sounded promising - because I could explicitly specify which method to call. But it didn't 'send' any thing, it just called this method directly from the same thread.

Am I understanding this right? Do I have to push some sort of a custom event (perhaps NSEventTypeApplicationDefined) to the main thread queue for this to work properly? And if so, how to I respond to custom events like that?


Solution

  • Like this:

    dispatch_async(dispatch_get_main_queue(), ^{
       // do whatever
    });