4
我卡住了!帶塊完成處理程序的自定義模態窗口
我想創建一個自定義模式對話框。我希望它使用塊作爲完成處理程序與NSSavePanel類似地執行。
我只複製了我認爲需要的重要片段。
@implementation ModalWindowController
- (void)makeKeyAndOrderFront:(id)sender
modalToWindow:(NSWindow*)window
sourceRect:(NSRect)rect
completionHandler:(void (^)(NSInteger result))handler {
_handler = [handler retain];
session = [NSApp beginModalSessionForWindow:[self window]];
[[NSApplication sharedApplication] runModalSession:session];
[[self window] makeKeyAndOrderFrontCentered:self expandingFromFrame:rect];
}
- (IBAction)okButtonPressed:(id)sender {
[[self window] orderOut:self];
_handler(NSOKButton);
[NSApp endModalSession:session];
}
@end
現在,我可以把這個使用的代碼:
[self.modalWindowController makeKeyAndOrderFront:self
modalToWindow:[[self view] window]
sourceRect:sr
completionHandler:^(NSInteger result) {
NSLog(@"Inside Block");
if (result == NSOKButton) {
// do something interesting here
}
}];
NSLog(@"Errg");
一切順利然而,該方法makeKeyAndOrderFront後:modalToWindow:sourceRect:completionHandler:已完成它不會阻塞線程,因此「即使用戶未選擇「確定」或「取消」,也會打印「錯誤」。此時將顯示模態窗口,用戶單擊確定,然後執行_handler塊。但是,如果我試圖訪問塊中的局部變量,並且應用程序崩潰,因爲已經清理了所有內容。
什麼是從makeKeyAndOrderFront阻止主線程的最佳方法:...方法?這是使用塊實現完成處理程序的正確方法嗎?
嗨Yuji,感謝您的信息!這解決了這個問題。 – 2010-01-26 22:11:21