views:

88

answers:

1

I want to create a separate thread that runs its own window. Frankly, the documentation does not make sense to me.

So I create an NSThread with a main function. I start the thread, create an NSAutoreleasePool, and run the run loop:

// Global:
BOOL shouldKeepRunning = YES;

- (void)threadMain {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    // Load a nib file, set up its controllers etc.
    while (shouldKeepRunning) {
        NSAutoreleasePool *loopPool = [NSAutoreleasePool new];
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
        [loopPool drain];
    }
    [pool drain];
}

But since there is no registered port or observer, runUntilDate: exits immediately and CPU utilization goes to 100%.

All thread communication is handled by calls to performSelector:onThread:withObject:waitUntilDone:. Clearly, I am not using the API correctly. So, what am I doing wrong?

+4  A: 

Much of AppKit is not thread-safe and will not work properly (1) when manipulated outside the main thread. You will find only pain and misery trying to ignore this fact.

What are you really trying to do that requires a different thread for this window? Are you merely trying to keep a responsive UI? If so, there're much better ways of doing it. See NSOperation / NSOperationQueue (where "units of work" and "queues" are the focus, not "this window shall run on this thread, etc.").

I'd recommend restating your question with your specific goal detailed clearly.

(1) For some classes, it takes a lot of careful work. For others, they are quite firmly off limits.

Joshua Nozzi
really, I am to build a GUI in a separate thread as a requirement of some porter-from-Windows API.
BastiBechtold
Reality remains: AppKit is generally not thread-safe. The only sane porting approach for a Mac-like app that doesn't run like ass is to port the core functionality as best you can and build the rest according to the platform.
Joshua Nozzi
That's what I say, man.
BastiBechtold
My boss finally agreed to do the GUI stuff on the main thread ;-)
BastiBechtold
"My boss finally agreed the sky is blue." Good of him/her to accept reality, I suppose ...
Joshua Nozzi