gpt4 book ai didi

Cocoa:如何在执行后台任务时运行模式窗口?

转载 作者:行者123 更新时间:2023-12-03 16:24:05 24 4
gpt4 key购买 nike

我尝试过打电话

modalSession=[NSApp beginModalSessionForWindow:conversionWindow];
[NSApp runModalForWindow:conversionWindow];

为了获得一个模态转换窗口,阻止用户与应用程序的其余部分交互,但这似乎也会阻止代码执行。我的意思是上面显示的代码后面的代码根本没有执行。我怎样才能解决这个问题?我确信这是可能的,因为许多应用程序在执行一些大任务(例如视频转换等)时显示出一些进展...

最佳答案

除非绝对必要,否则请不要使用应用模式窗口。如果可能的话,使用一张纸。但是,如果必须使用模式对话框,则可以在模式对话框打开时给主运行循环一些时间来运行它:

NSModalSession session = [NSApp beginModalSessionForWindow:[self window]];
int result = NSRunContinuesResponse;

while (result == NSRunContinuesResponse)
{
//run the modal session
//once the modal window finishes, it will return a different result and break out of the loop
result = [NSApp runModalSession:session];

//this gives the main run loop some time so your other code processes
[[NSRunLoop currentRunLoop] limitDateForMode:NSDefaultRunLoopMode];

//do some other non-intensive task if necessary
}

[NSApp endModalSession:session];

如果您的 View 需要主运行循环才能运行(例如WebView),这非常有用。

但是,请理解模态 session 就是这样,调用 beginModalSessionForWindow: 之后的任何代码都不会执行,直到模态窗口关闭并且模态 session 结束为止。结束。这是不使用模式对话框的一个很好的理由。

请注意,您不能在上面代码中的 while 循环中执行任何重要工作,因为这样您将阻塞模态 session 以及主运行循环,这会将您的应用程序变成沙滩球城。

如果你想在后台做一些实质性的事情,你必须使用某种形式的并发,例如使用 NSOperation、GCD 后台队列或只是一个普通的后台线程。

关于Cocoa:如何在执行后台任务时运行模式窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7246153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com