开发者

How to create a run loop that only listens to performSelector:onThread: and GUI events?

开发者 https://www.devze.com 2022-12-27 06:36 出处:网络
I want to create a separate thread that runs its own window. Frankly, the documentation does not make sense to me.

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 (shou开发者_运维百科ldKeepRunning) {
        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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消