Search code examples
objective-cmacoscocoacomboboxnsalert

Passing NSComboBox value that is inside a NSAlert Sheet


I have a NSAlert Sheet that has a NSComboBox inside. How can i pass the combo box value when the user has pressed a button of the NSAlert?
code:

NSComboBox* comboBox = [[NSComboBox alloc] initWithFrame:NSMakeRect(0, 0, 150, 26)];
        [comboBox setTitleWithMnemonic:@"2"];

        for (int i=2; i<[array count]+1; i++){
            [comboBox addItemWithObjectValue:[NSString stringWithFormat:@"%i", i]];
        }

        [comboBox setEditable:NO];

        NSAlert *alert = [[NSAlert alloc] init];
        [alert addButtonWithTitle:@"Okay"];
        [alert addButtonWithTitle:@"Cancel"];
        [alert setMessageText:@"Choose a number"];
        [alert setAccessoryView:comboBox];
        [alert beginSheetModalForWindow:_window modalDelegate:self didEndSelector:@selector(alertToChooseX:returnCode:contextInfo:) contextInfo:nil];

- (void)alertToChooseX:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
    if (returnCode == NSAlertFirstButtonReturn) {
        NSLog(@"Pressed Okay");
    }
}

Solution

  • Describe comboBox in Your header file and after pushed button "Okay" take it's value like this:

    in .h

    NSComboBox *comboBox;
    

    in .m

    comboBox = [[NSComboBox alloc] initWithFrame:NSMakeRect(0, 0, 150, 26)];
    [comboBox setTitleWithMnemonic:@"2"];
    .... // Your all code goes here
    


    - (void)alertToChooseX:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
        if (returnCode == NSAlertFirstButtonReturn) {
            NSLog(@"Pressed Okay");
    
            NSLog(@"Selected ComboBox's String Value: %@", [comboBox stringValue]);
            NSLog(@"Selected ComboBox's Object Value: %@", [comboBox objectValueOfSelectedItem]);
            NSLog(@"Selected ComboBox's Item Index: %ld", [comboBox indexOfSelectedItem]);
        }
    }
    

    Note: Don't forget to release comboBox because it's allocating memory.