I am stuck!
I am trying to create my own modal dialogue. I would like it to execute in the same way as the NSSavePanel, using the block as a completion handler.
I copied only the important fragments that I think are necessary.
@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
Now I can call this using the code:
[self.modalWindowController makeKeyAndOrderFront:self modalToWindow:[[self view] window] sourceRect:sr completionHandler:^(NSInteger result) { NSLog(@"Inside Block"); if ( result == NSOKButton ) {
Everything is going well, however, after the makeKeyAndOrderFront: modalToWindow: sourceRect: completeHandler: method has completed, it does not block the stream, so "Errg" will be printed even if the user did not select "ok" or "cancel". The modal window is displayed at this moment when the user clicks “OK” and then the _handler block is executed. However, if I try to access the local variables in the block, and the application crashes because everything is already cleared.
What is the best approach to blocking the main thread from makeKeyAndOrderFront: ... method? Is this the right approach to implement a completion handler using blocks?
source share