Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox State Problem

I'm new to Cocoa, and working my way through Hillegass's book. I'm having trouble with chapter 20's challenge 2.

The challenge is to add checkbox's that toggle if the letter being drawn is italic, bold, or both.

-(IBAction)toggleItalic:(id)sender
{
int state = [italicBox state];
NSLog(@"state %d", state);
if (state = 1) {
    italic = YES;
    NSLog(@"italic is yes");
}
else {
    italic = NO;
    NSLog(@"italic is no");

}
}

Right now, this snippet of code is returning yes when the box is checked, and when the box is unchecked. What am I doing wrong?

Thanks,

Justin.

like image 900
Jwoodbridge Avatar asked May 16 '26 14:05

Jwoodbridge


2 Answers

Your problem lies in your if statement:

if (state = 1) {

you are assigning state to the value 1: state = 1, while what you need to test is if state is currently 1: state ==1

This is a fairly common mistake (especially in languages that allow assignment in if statements). One trick to learn to get around this is to make your comparison checks like so:

if (1 == state) 

You cannot assign 1 to another value. Therefore, if you mistakenly use = instead of == you will get a compiler error and it's an easy fix.

like image 86
MarkPowell Avatar answered May 18 '26 09:05

MarkPowell


Use comparison instead of assignment and use proper enums instead of hardcoded values that could change:

if (state == NSOnState)
else if (state == NSOffState)
like image 36
stefanB Avatar answered May 18 '26 10:05

stefanB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!