It appears that in iOS I have a number of options that seem to fit for boolean values:
YES
NO
TRUE
FALSE
true
false
Which ones should I use? In this particular case I'm hiding a label, so should I set the hidden
property to YES
, TRUE
, or true
?
Short answer: you should prefer YES
and NO
for setting foundation properties of type BOOL
.
For the long answer, let's first see where are these constants defined:
true
and false
are from stdbool.h
; they are #define
-d as 1
and 0
TRUE
and FALSE
are from CFBase.h
; they are #define
-d as 1
and 0
YES
and NO
are from NSObjCRuntime.h
. This is where signed char
is typedef
-ed as BOOL
, and its two values are #define
-d as ((BOOL)1)
and ((BOOL)0)
or __objc_yes
/__objc_no
if objc_bool
is supported.The foundation classes consistently use BOOL
, which is a typedef
for signed char
, to represent its boolean properties. Since the first two pairs get converted to int
constants, using them may result in warnings, though it would probably work correctly anyway. The YES
and NO
constants, however, are defined in the most compatible way for your compiler, regardless of its version. Therefore, I would recommend using YES
and NO
consistently throughout your code.
Actually there is no difference between YES
, TRUE
and true
those all represent a true state represented by 1.
And NO
, false
, FALSE
is represents a false state represented by 0.
You can also use:
BOOL aBool = 1;
which is equivalent to BOOL aBool = true;
and BOOL aBool = TRUE;
and BOOL aBool = YES;
But:
BOOL bBool = 7;
if (bBool)
{
NSLog(@"bBool is YES!\n");
}
if (bBool != YES) {
NSLog("bBool is not YES!\n");
}
Will output like:
b is YES!
b is not YES!
This is because direct comparison with YES will fail when the value of a BOOL
type is a non-zero value other than 1.
Here is a nice article for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With