views:

105

answers:

2

Hello,

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.

+7  A: 

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.

MarkPowell
+1 for correctness. In addition, you should be using the enums `NSOnState` and `NSOffState` instead of the numerical values directly. Avoid magic numbers. =)
Dave DeLong
Same goes for comparing against nil/NULL or any other kind of constants. In C-style languages, it's wise to always put the constant first ( `if (nil == someObject)` will save you so much trouble).
jbrennan
You can also turn on a compiler warning, `-Wparentheses` in GCC or “Missing Braces and Parentheses” in Xcode, that will warn you any time you make this mistake. You can add an extra pair for cases where you really do mean this (e.g., “`if ((self = [super init]))`”). And there's a compiler option, `-Werror`/“Treat Warnings as Errors”, that will make any warning—including this one—break your build, so that you can't miss or ignore it.
Peter Hosey
A: 

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

if (state == NSOnState)
else if (state == NSOffState)
stefanB