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
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.
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.
I think all of them are okay. But personally, I'd like to use YES
/NO
.
I found a doc called Objective-C Runtime Reference:
Boolean Values These macros define convenient constants to represent Boolean values.
#define YES (BOOL)1
#define NO (BOOL)0Constants
YES
Defines YES as 1.
Available in iOS 2.0 and later.
Declared in NSObjCRuntime.h.NO
Defines NO as 0.
Available in iOS 2.0 and later.
Declared in NSObjCRuntime.h.Declared In
objc.h
I share your view on this, whilst they are currently all defined the same, porting the code is a pain when you may find TRUE != true. (Precisely why we should never test X == 1 for TRUE as some languages use -1 and some use 1)
I think it might be personal preference and mainly about future ports.
I follow the TRUE and FALSE options so that porting to C/C++ is easier.
You may find that true and false is better if you're regularly converting code to Java so there's less search/replaces but I found consistency with Cocoa easier.
Use YES and NO is the same to use TRUE and FALSE or 1 and 0 respectively.
And use NSLog to view result like this little example:
BOOL result;
result = YES;
NSLog(@"my boolean result is %@",result ? @"Yes" : @"No");