Is there any difference between bool, Boolean, and BOOL in Objective-C?
I know BOOL is actually a ty开发者_开发知识库pedef of signed char, but what about Boolean?
What is the difference between bool, Boolean and BOOL?
Boolean
is an old Carbon keyword (historic Mac type), defined as an unsigned char
. BOOL
is an Objective-C type defined as signed char
. bool
is a defined version of the _Bool
standard C type. It's defined as an int
. Use BOOL
.
Edit (2019): Apple talks about the underlying implementation of BOOL
in some new documentation. Basically, on macOS, BOOL
is still ultimately a signed char
, but on iOS and related platforms, it a native C bool
underneath.
I don't want to take away from @JonShier's useful answer, but I've more to add than fits well in a comment...
bool
Introduced to standard C in the C99 spec. (The C99 standard was published in 1999, but it took some years after that to become widespread in use.) Prior to that, "plain" C had no built-in Boolean type, so libraries that built on top of C often defined their own. (And often continued using their own types for source/binary compatibility even after they embraced C99 compilers.)
Use this if you're writing ISO C and aren't working in the context of higher level libraries with their own Boolean types.
Boolean
Defined by Carbon (the early-OSX-days compatibility bridge from the even older Mac Toolbox), which you might still see in some projects (due to transitive #include
of headers that are really only around for compatibility with really old source code).
Don't use this.
BOOL
Defined by ObjC because NeXTSTEP needed its own Boolean type back in 1988. (The oldest objc.h
I can find on my office bookshelf dates to 1992 and includes a definition of BOOL
.)
ObjC BOOL
has often been defined as typedef signed char
, meaning that it can hold more values than just YES
(1) and NO
(0). That can be a problem if you aren't careful. (Why even do that? Because if a type is one bit wide, it's hard to pack into well-aligned memory for good performance.)
However, in iOS 64-bit (including tvOS) and watchOS, the compiler defines OBJC_BOOL_IS_BOOL
, which makes ObjC BOOL
just an alias for C99 bool
. That means the language/compiler ensures that nonzero values are always stored as 1, so you don't have the issues that come from typedef signed char BOOL
. (Still gotta worry about them on macOS or 32-bit iOS, though.)
TLDR
If you're working in ObjC with ObjC frameworks (like Cocoa, UIKit, etc), you should use BOOL
for consistency with the APIs you're interacting with. (Besides, YES
and NO
are much louder than true
and false
, and it's good to be emphatic when you're talking about absolute truth, right?)
If your new APIs have no need to interact with old ones, bool
is more specific and clear than BOOL.
When building an non-Mac application with Xcode 9, BOOL v = 2; NSLog(@"%d", v);
outputs "1", not "2".
Reference to Apple documentation
精彩评论