All types of booleans in ObjectiveC
Possible duplicate:
What values should I use for iOS boolean states?
I believe there are something like 5 boolean types in the iOS environment (which come from C, C ++ and Objective C).
- _Bool
- Bool
- Bool
- boolean_t
- Boolean
And there are at least four pairs of values for them:
- true, false
- TRUE FALSE
- WELL NO
- ten
What do you think is the best (style wise) for iOS Objective C development?
Update 1
I mentioned the "boolean" type. It looks like it's not there. I removed it from the list and added _Bool.
I am aware of the typedef for these types and values. It's about style differences.
source to share
iOS and OS X are mostly composed of Cocoa, which use a boolean type BOOL
with values YES
/ NO
.
BOOL
- Defined by C ++.
- A true boolean value, guaranteed to be 0 or 1.
_Bool
- Defined by C99.
- A true boolean value, guaranteed to be 0 or 1.
- If stdbool.h is included, bool #defined as _Bool.
BOOL
- Defined in the Objective-C framework with
/usr/include/objc/objc.h
. - A
signed char
in 32 bits. Values can beYES
(0x01),NO
(0x00), or anything in the range -127 to 128.YES
/ areNO
defined in<Foundation/NSObjCRuntime.h>
. - A
BOOL
in 64 bits, guaranteed 0 or 1.
Boolean
dt> <Dd>
- Defined by Carbon at CFBase.h .
- Unsigned char.
- Values can be
TRUE
(0x01),FALSE
(0x00), or anything in the range -127 to 128.
boolean_t
- Defined
/usr/include/mach/i386/boolean.h
- int in x32 or unsigned int in x64.
For invalid boolean types:
- Any non-zero value is considered true in logical expressions.
- If you are using booleans with a smaller range than the cast type, only the lower bytes are used.
Cases where one type or the other matter is hard to imagine. There are a few cases where casting to BOOL can bite you, as well as some rare situations (for example: KVO converts BOOL to NSNumber and bool to CFBoolean). Anyway, when you use BOOL consistently, you will be considered in case Apple changes its definition.
source to share
Use BOOL
and YES
/ NO
in Objective-C code. This is expected in Objective-C code and how Objective-C headers define the data type. (Note that sometimes you can deal with other types / values, for example, when checking the "truthfulness" of pointers or when working with code, for example in C ++, but Objective-C usually uses BOOL
and YES
/ NO
for types and values boolean data.)
source to share
It is basically totally indifferent. In practice, I'm sure they even announced the same: typedef signed char BOOL;
, typedef signed char Boolean;
etc.
Thus, they are practically compatible and equivalent; however, the best approach is to respect methods like expect and return, so write
[object someObjectiveCMethod:YES];
instead
[object someObjectiveCMethod:TRUE];
and
CFWhateverSetBooleanProperty(true);
instead
CFWhateverSetBooleanProperty(YES);