Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check state of NSCheckbox created programmatically in cocoa

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".

like image 365
user2656381 Avatar asked Dec 20 '22 01:12

user2656381


1 Answers

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");
    }
}
like image 92
Martin R Avatar answered May 19 '23 02:05

Martin R