Can someone please educate me why the following does not work? The button never gets set to selected.
[self.boldButton setSelected:isBold];
If I replace the above with an if else statement it works fine. I can also change the setSelected values to 1 or 0, instead of YES or NO and it still works fine.
if (isBold)
{
[self.boldButton setSelected:YES];
}
else
{
[self.boldButton setSelected:NO];
}
So I have a working project, but I don’t understand why these two implementations don’t deliver the same results. Thanks.
FWIW – I test for bold with another method. Though if the test were flawed, I don’t see how the second approach could work, while the first still doesn’t.
- (BOOL)isBold
{
CTFontRef fontRef = (CTFontRef)CFBridgingRetain(self);
CTFontSymbolicTraits symbolicTraits = CTFontGetSymbolicTraits(fontRef);
return (symbolicTraits & kCTFontTraitBold);
}
BOOLis defined like this in<objc/objc.h>:That means a
BOOLcan actually hold any value in the range -128 through 127 (inclusive).-[UIControl setSelected:]works roughly like this:(I disassembled the simulator version of
UIKitwith Hopper to figure that out.)So, notice two things:
The
ifstatement condition can only be true ifselected == 0orselected == 1. It will never be true ifselectedhas any other value.The assignment statement (that updates
_controlFlags) only uses bit 0 (the 1’s bit) ofselected. So, for example, ifselected == -2, which is logically true in C and has every bit set except bit 0, the assignment statement will still not turn on the bit in_controlFlags.This means that you must pass 0 or 1 to
-[UIControl setSelected:]. No other value will work reliably.The shortest way to convert all non-zero values to 1 in C is by applying the
!operator twice:However, it would probably be better to fix your
-isBoldmethod to return a “safe”BOOLinstead: