How to check state of NSCheckbox created programmatically in cocoa

cocoa, macos, objective-c

Solution

You have to check the state of the sending button, not of the instance variable `DeleteCheckbox` (which has been released and does not point to a valid button):

-(IBAction)checkState:(NSButton *)sender
{
    if ([sender state] == NSOnState) {
        NSLog(@"selected");
    }
    else {
        NSLog(@"not selected");
    }
}

Problem

I created Multiple checkbox dynamic, now I want to check state of them but I don't know how to do that. This is my code to create multiple NSCheckbox: ``` for(int i=1; i<=number;i++) { DeleteCheckbox = [[NSButton alloc] initWithFrame:NSMakeRect (20,textfield_Y,50,25)]; [DeleteCheckbox setButtonType:NSSwitchButton]; [DeleteCheckbox setBezelStyle:0]; [DeleteCheckbox setTitle:@""]; [DeleteCheckbox setTag:200+i]; [DeleteCheckbox setState:NSOffState]; [DeleteCheckbox setAction:@selector(checkState:)]; [guiView addSubview:DeleteCheckbox]; [DeleteCheckbox release]; } ``` And below code for check state: ``` -(IBAction)checkState:(id)sender { if ([DeleteCheckbox state] == NSOnState) { NSLog(@"selected"); } else { NSLog(@"not selected"); } } ``` But when run, it always printf: "not selected".

Original source