,除非絕對必要,請不要使用應用程序模式窗口。如果可能,請使用表格。但是,如果你必須使用一個模式對話框,您可以通過給它運行一段時間的主要運行循環,而模態對話框打開時:
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
)。
但是,要明白模態會話就是這樣,之後的任何代碼都不會被執行,直到模態窗口關閉並且模態會話結束。這是不使用模態對話框的一個非常好的理由。
請注意,您不得在上述代碼的while
循環中執行任何重要工作,因爲那樣您將阻止您的模式會話以及主運行循環,這會將您的應用程序變成沙灘球城市。
如果你想在後臺做一些實質性的事情,你必須使用某種形式的併發,比如使用NSOperation
,GCD背景隊列或者純粹的後臺線程。
感謝您的詳盡答覆。我想我會忘記模式窗口(我從來不喜歡它們)。 – Nickkk