오브젝티브 -C : BOOL vs Bool
"신형"
BOOL
(
YES
,
NO
)을 보았습니다 .나는이 유형이 거의 문자와 같다는 것을 읽었습니다.테스트를 위해 나는 :
NSLog(@"Size of BOOL %d", sizeof(BOOL));
NSLog(@"Size of bool %d", sizeof(bool));
두 로그 모두에 "1"이 표시되는 것을 확인하는 것이 좋습니다 (때로는 C ++ bool은 int이고 sizeof는 4 임).그래서 부울 유형이나 무언가에 문제가 있는지 궁금합니다.속도를 잃지 않고 부울을 사용할 수 있습니까?
의 정의에서
objc.h
:
#if (TARGET_OS_IPHONE && __LP64__) || TARGET_OS_WATCH
typedef bool BOOL;
#else
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#endif
#define YES ((BOOL)1)
#define NO ((BOOL)0)
예, BOOL이 문자라고 가정 할 수 있습니다. (C99)
bool
유형을 사용할 수 있지만 모든 Apple Objective-C 프레임 워크 및 대부분의 Objective-C / Cocoa 코드는 BOOL을 사용하므로 BOOL을 사용하여 typedef가 변경되면 두통을 피할 수 있습니다.
위에서 언급했듯이 BOOL은 부호가있는 문자입니다. bool-C99 표준 (int)의 유형입니다.BOOL-예 / 아니요. 부울-참 / 거짓.예를보십시오 :
bool b1 = 2;
if (b1) printf("REAL b1 \n");
if (b1 != true) printf("NOT REAL b1 \n");
BOOL b2 = 2;
if (b2) printf("REAL b2 \n");
if (b2 != YES) printf("NOT REAL b2 \n");
결과는
실제 b1
실제 b2 실제 b2
아님
bool! = BOOL입니다. 아래 결과는 ONCE AGAIN-REAL b2 에만 해당됩니다.
b2 = b1;
if (b2) printf("ONCE AGAIN - REAL b2 \n");
if (b2 != true) printf("ONCE AGAIN - NOT REAL b2 \n");
bool을 BOOL로 변환하려면 다음 코드를 사용해야합니다
BOOL b22 = b1 ? YES : NO; //and back - bool b11 = b2 ? true : false;
따라서 우리의 경우 :
BOOL b22 = b1 ? 2 : NO;
if (b22) printf("ONCE AGAIN MORE - REAL b22 \n");
if (b22 != YES) printf("ONCE AGAIN MORE- NOT REAL b22 \n");
그리고 우리는 지금 무엇을 얻습니까? :-)
글을 쓰는 시점에서 이것은 최신 버전의 objc.h입니다.
/// Type to represent a boolean value.
#if (TARGET_OS_IPHONE && __LP64__) || TARGET_OS_WATCH
#define OBJC_BOOL_IS_BOOL 1
typedef bool BOOL;
#else
#define OBJC_BOOL_IS_CHAR 1
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#endif
즉, 64 비트 iOS 기기와 WatchOS
BOOL
는
bool
다른 모든 기기 (OS X, 32 비트 iOS)와 동일하지만
signed char
컴파일러 플래그로 재정의 할 수 없습니다.
-funsigned-char
또한이 예제 코드는 다른 플랫폼에서 다르게 실행된다는 것을 의미합니다 (자체 테스트 한 결과).
int myValue = 256;
BOOL myBool = myValue;
if (myBool) {
printf("i'm 64-bit iOS");
} else {
printf("i'm 32-bit iOS");
}
BTW 는 가능한 값의 약 0.4 %가 음수가되기 때문에 변수 와 같은
array.count
것을 할당하지 않습니다
BOOL
.
The Objective-C type you should use is BOOL
. There is nothing like a native boolean datatype, therefore to be sure that the code compiles on all compilers use BOOL
. (It's defined in the Apple-Frameworks.
Yup, BOOL is a typedef for a signed char according to objc.h.
I don't know about bool, though. That's a C++ thing, right? If it's defined as a signed char where 1 is YES/true and 0 is NO/false, then I imagine it doesn't matter which one you use.
Since BOOL is part of Objective-C, though, it probably makes more sense to use a BOOL for clarity (other Objective-C developers might be puzzled if they see a bool in use).
Another difference between bool and BOOL is that they do not convert exactly to the same kind of objects, when you do key-value observing, or when you use methods like -[NSObject valueForKey:].
As everybody has said here, BOOL is char. As such, it is converted to an NSNumber holding a char. This object is indistinguishable from an NSNumber created from a regular char like 'A' or '\0'. You have totally lost the information that you originally had a BOOL.
However, bool is converted to an CFBoolean, which behaves the same as NSNumber, but which retains the boolean origin of the object.
I do not think that this is an argument in a BOOL vs. bool debate, but this may bite you one day.
Generally speaking, you should go with BOOL, since this is the type used everywhere in the Cocoa/iOS APIs (designed before C99 and its native bool type).
The accepted answer has been edited and its explanation become a bit incorrect. Code sample has been refreshed, but the text below stays the same. You cannot assume that BOOL is a char for now since it depends on architecture and platform. Thus, if you run you code at 32bit platform(for example iPhone 5) and print @encode(BOOL) you will see "c". It corresponds to a char type. But if you run you code at iPhone 5s(64 bit) you will see "B". It corresponds to a bool type.
I go against convention here. I don't like typedef's to base types. I think it's a useless indirection that removes value.
- When I see the base type in your source I will instantly understand it. If it's a typedef I have to look it up to see what I'm really dealing with.
- When porting to another compiler or adding another library their set of typedefs may conflict and cause issues that are difficult to debug. I just got done dealing with this in fact. In one library boolean was typedef'ed to int, and in mingw/gcc it's typedef'ed to a char.
As mentioned above BOOL
could be an unsigned char
type depending on your architecture, while bool
is of type int
. A simple experiment will show the difference why BOOL and bool can behave differently:
bool ansicBool = 64;
if(ansicBool != true) printf("This will not print\n");
printf("Any given vlaue other than 0 to ansicBool is evaluated to %i\n", ansicBool);
BOOL objcBOOL = 64;
if(objcBOOL != YES) printf("This might print depnding on your architecture\n");
printf("BOOL will keep whatever value you assign it: %i\n", objcBOOL);
if(!objcBOOL) printf("This will not print\n");
printf("! operator will zero objcBOOL %i\n", !objcBOOL);
if(!!objcBOOL) printf("!! will evaluate objcBOOL value to %i\n", !!objcBOOL);
To your surprise if(objcBOOL != YES)
will evaluates to 1 by the compiler, since YES
is actually the character code 1, and in the eyes of compiler, character code 64 is of course not equal to character code 1 thus the if statement will evaluate to YES/true/1
and the following line will run. However since a none zero bool
type always evaluates to the integer value of 1, the above issue will not effect your code. Below are some good tips if you want to use the Objective-C BOOL
type vs the ANSI C bool
type:
- Always assign the
YES
orNO
value and nothing else. - Convert
BOOL
types by using double not!!
operator to avoid unexpected results. - When checking for
YES
useif(!myBool) instead of if(myBool != YES)
it is much cleaner to use the not!
operator and gives the expected result.
Also, be aware of differences in casting, especially when working with bitmasks, due to casting to signed char:
bool a = 0x0100;
a == true; // expression true
BOOL b = 0x0100;
b == false; // expression true on !((TARGET_OS_IPHONE && __LP64__) || TARGET_OS_WATCH), e.g. MacOS
b == true; // expression true on (TARGET_OS_IPHONE && __LP64__) || TARGET_OS_WATCH
If BOOL is a signed char instead of a bool, the cast of 0x0100 to BOOL simply drops the set bit, and the resulting value is 0.
참고URL : https://stackoverflow.com/questions/541289/objective-c-bool-vs-bool
'programing' 카테고리의 다른 글
ES6에서 "엄격한 사용"을 사용하지 않는 것이 좋습니까? (0) | 2020.05.14 |
---|---|
샤딩이란 무엇이며 왜 중요합니까? (0) | 2020.05.14 |
Express.js에서 res.send와 res.json의 차이점 (0) | 2020.05.14 |
git repo의 하위 디렉토리에 대한 git log history를 표시하는 방법은 무엇입니까? (0) | 2020.05.14 |
SQL Server 동적 PIVOT 쿼리? (0) | 2020.05.14 |