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.
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.
Use comparison instead of assignment and use proper enums instead of hardcoded values that could change:
if (state == NSOnState)
else if (state == NSOffState)
精彩评论