Cocoa:如何在执行后台任务时运行模式窗口? [英] Cocoa: how to run a modal window while performing a background task?

查看:15
本文介绍了Cocoa:如何在执行后台任务时运行模式窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过打电话

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

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

in order to get a modal conversionWindow that prevents the user to interact with the rest of the application, but this also seems to block code execution. What I mean is that the code that comes after the code shown above isn't executed at all. How can I fix this? I'm sure this is possible because many applications show some progress while performing some big task, like video conversion etc...

推荐答案

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

Please don't use an app-modal window unless it's absolutely necessary. Use a sheet if possible. However, if you must use a modal dialog, you can make the main run loop run by giving it some time while the modal dialog is open:

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];

如果您的视图需要主运行循环才能运行(想到 WebView),这将非常有用.

This is very useful if you have views that require the main run loop to operate (WebView comes to mind).

但是,要了解模态会话就是这样,在模态窗口关闭和模态会话之前, 调用 beginModalSessionForWindow: 的任何代码都不会执行结束.这是不使用模式对话框的一个很好的理由.

However, understand that a modal session is just that, and any code after the call to beginModalSessionForWindow: will not be executed until the modal window closes and the modal session ends. This is one very good reason not to use modal dialogs.

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

Note that you must not do any significant work in the while loop in the code above, because then you will block your modal session as well as the main run loop, which will turn your app into beachball city.

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

If you want to do something substantial in the background you must use some form of concurrency, such as a using NSOperation, a GCD background queue or just a plain background thread.

这篇关于Cocoa:如何在执行后台任务时运行模式窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆