Mike
Mike

Reputation: 301

How to close NSOpenPanel

I need to open a text file and process each line in it. I cannot get NSOpenPanel to close so I can proceed with the processing. The below incorporates code I found here from a couple of years ago, and I am hoping someone has discovered a different way. NSSavePanel performs as expected, closing when a button is clicked.

- (IBAction)loadSettings:(id)sender
{
    NSString *t = [self splitSettings:@"k"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 100), dispatch_get_main_queue(), ^(void){
        // some other method calls here
    });    
    int i = 4;   // so I have a breakpoint
}

- (NSString*)splitSettings:(NSString*)inFile
{
    NSOpenPanel *zOpenPanel = [NSOpenPanel openPanel];
    NSArray *arrayOfExtensions = [NSArray arrayWithObject:@"txt"];
    [zOpenPanel setAllowedFileTypes:arrayOfExtensions];
    NSInteger intResult = [zOpenPanel runModal];
    if (intResult == NSFileHandlingPanelCancelButton) {
        NSLog(@"readUsingOpenPanel cancelled");
        return @"Cancelled";
    }
    NSURL *zUrl = [zOpenPanel URL];
    // read the file
    NSString * zStr = [NSString stringWithContentsOfURL:zUrl                                                                                             encoding:NSASCIIStringEncoding                                                                                                 error:NULL];
    return zStr;
}

Upvotes: 1

Views: 648

Answers (1)

Daniel Farrell
Daniel Farrell

Reputation: 9740

Check out my example project here that I used to figure this stuff out, CocoaSheets. But note that this is for the general case of using any modal sheet, not just a NSOpenPanel. Maybe someone will post NSOpenPanel specific case, in any case this should help I hope.

Start the modal window using,

[[self window] beginSheet:self.sheetWindowController.window completionHandler:^(NSModalResponse returnCode) {

    switch (returnCode) {

        case NSModalResponseCancel:
            NSLog(@"%@", @"NSModalResponseCancel");
            break;

        case NSModalResponseOK:
            NSLog(@"%@", @"NSModalResponseOK");
            break;

        default:
            break;
}}];

Then you wire the cancel and OK buttons to the following action methods. Notice the you use sheetParent to end the sheet.

- (IBAction)cancelButtonAction:(id)sender {
    [[[self window] sheetParent] endSheet:self.window returnCode:NSModalResponseCancel];
}

- (IBAction)OKButtonAction:(id)sender {
    [[[self window] sheetParent] endSheet:self.window returnCode:NSModalResponseOK];
}

Upvotes: 1

Related Questions