objective-c에서 YES / NO, TRUE / FALSE와 true / false 사이에 차이가 있습니까?
간단한 질문은 정말로; 이 값들 사이에 차이가 있습니까 (그리고 BOOL과 bool 사이에 차이가 있습니까)? 동료는 Objective-C에서 다른 것으로 평가한다고 언급했지만 각각의 .h 파일에서 typedef를 볼 때 YES / TRUE / true는 모두 정의 1
되었고 NO / FALSE / false는 모두로 정의되었습니다 0
. 실제로 어떤 차이가 있습니까?
실질적인 차이가 없습니다 제공 당신이 사용하는 BOOL
논리 값으로 변수. C는 0으로 평가되는지 여부에 따라 부울 표현식을 처리합니다. 따라서 :
if(someVar ) { ... }
if(!someVar) { ... }
와 같은 의미
if(someVar!=0) { ... }
if(someVar==0) { ... }
그렇기 때문에 기본 유형이나 표현식을 부울 테스트 (예 : 포인터 포함)로 평가할 수 있습니다. 후자는 아니라 전자를해야합니다.
참고가 있다는 것입니다 당신이 소위에 둔각 값을 할당하면 차이 BOOL
때문에 항상 논리 값으로 사용할하고 그들의에서 그들을 지정, 특정 값에 대한 변수 테스트 #define
값.
중요한 것은 문자 비교를 사용하여 부울을 테스트하지 마십시오. 예가 someVar
아닌 0이 아닌 값을 할당 할 수 있기 때문에 위험 할뿐만 아니라 더 중요한 것은 의도를 올바르게 표현하지 못하는 것입니다.
if(someVar==YES) { ... } // don't do this!
if(someVar==NO ) { ... } // don't do this either!
다시 말해, 사용하도록 의도되고 문서화 된 구성을 사용하면 C의 상처에서 벗어날 수 있습니다.
와 사이에 차이 가 있다고 생각 하는 이유는 다음 웹 페이지에서 확인하십시오. http://iosdevelopertips.com/objective-c/of-bool-and-yes.htmlbool
BOOL
프리미티브 유형 BOOL
이 아니기 때문에 unsigned char
유형의 변수는 및 BOOL
이외의 값을 포함 할 수 있습니다 .YES
NO
이 코드를 고려하십시오.
BOOL b = 42;
if (b) {
printf("b is not NO!\n");
}
if (b != YES) {
printf("b is not YES!\n");
}
출력은 다음과 같습니다.
b는 아니요가 아닙니다!
b는 그렇습니다!
대부분의 사람들에게 이것은 불필요한 관심사이지만 실제로 부울을 원한다면을 사용하는 것이 좋습니다 bool
. 추가해야합니다 : iOS SDK는 일반적으로 BOOL
인터페이스 정의에서 사용하므로 BOOL
.
나는 이것에 대해 철저한 테스트를 수행했습니다. 내 결과는 스스로 말해야합니다.
//These will all print "1"
NSLog(@"%d", true == true);
NSLog(@"%d", TRUE == true);
NSLog(@"%d", YES == true);
NSLog(@"%d", true == TRUE);
NSLog(@"%d", TRUE == TRUE);
NSLog(@"%d", YES == TRUE);
NSLog(@"%d", true == YES);
NSLog(@"%d", TRUE == YES);
NSLog(@"%d", YES == YES);
NSLog(@"%d", false == false);
NSLog(@"%d", FALSE == false);
NSLog(@"%d", NO == false);
NSLog(@"%d", false == FALSE);
NSLog(@"%d", FALSE == FALSE);
NSLog(@"%d", NO == FALSE);
NSLog(@"%d", false == NO);
NSLog(@"%d", FALSE == NO);
NSLog(@"%d", NO == NO);
//These will all print "0"
NSLog(@"%d", false == true);
NSLog(@"%d", FALSE == true);
NSLog(@"%d", NO == true);
NSLog(@"%d", false == TRUE);
NSLog(@"%d", FALSE == TRUE);
NSLog(@"%d", NO == TRUE);
NSLog(@"%d", false == YES);
NSLog(@"%d", FALSE == YES);
NSLog(@"%d", NO == YES);
NSLog(@"%d", true == false);
NSLog(@"%d", TRUE == false);
NSLog(@"%d", YES == false);
NSLog(@"%d", true == FALSE);
NSLog(@"%d", TRUE == FALSE);
NSLog(@"%d", YES == FALSE);
NSLog(@"%d", true == NO);
NSLog(@"%d", TRUE == NO);
NSLog(@"%d", YES == NO);
출력은 다음과 같습니다.
2013-02-19 20:30:37.061 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.061 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.072 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.073 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.073 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.074 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.074 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.075 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.075 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.076 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.077 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.077 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.078 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.078 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.079 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.079 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.080 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.080 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.081 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.081 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.082 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.091 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.092 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.093 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.093 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.094 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.094 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.095 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.095 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.096 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.096 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.097 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.098 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.101 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.102 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.102 BooleanTests[27433:a0f] 0
이 질문에 대한 답변을 읽을 수도 있습니다 . 요약하면 오브젝티브 -C (objc.h의 정의에서) :
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#define OBJC_BOOL_DEFINED
#define YES (BOOL)1
#define NO (BOOL)0
주 (위험!) 차이가 사이 true
및 YES
JSON 직렬화에 있습니다.
예를 들어 JSON 유형의 서버 요청이 있으며 json sence로 true / false를 보내야합니다.
NSDictionary *r1 = @{@"bool" : @(true)};
NSDictionary *r2 = @{@"bool" : @(YES)};
NSDictionary *r3 = @{@"bool" : @((BOOL)true)};
그런 다음 다음을 보내기 전에 JSON 문자열로 변환합니다.
NSData *data = [NSJSONSerialization dataWithJSONObject:requestParams options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
결과는
jsonString1 // {"bool":1}
jsonString2 // {"bool":true}
jsonString3 // {"bool":true}
API 로직으로 인해 jsonString1
오류가 발생할 수 있습니다.
따라서 Objective-C의 부울에주의하십시오.
요약하면, 유형 이 정확 @YES
하고 캐스팅 된 값만 JSON 직렬화 로 변환됩니다 . (even ) 과 같은 다른 표현식 은 유형이 있으며 JSON으로 변환됩니다 .@((BOOL)expression)
__NSCFBoolean
true
@(expression1 && expression2)
@(YES && YES)
__NSCFNumber (int)
1
추신 당신은 단순히 문자열 값 부울을 사용할 수 있습니다
@{@"bool" : @"true"}; // in JSON {"bool":true}
아무도 언급하지 않은 미묘한 버그가 있습니다.
int i = 2;
if(i); //true
if(i==YES); // false
if((!!i)==YES); //true
여기서 문제는 그저 문제 (YES==1)
이며 C에서는 비교가 부울이 아니라 값을 기반으로하는 비교입니다.
because YES
is just a #define
(rather than something intrinsic to the language), it has to be some value, and 1
makes the most sense.
I think they add YES/NO to be more self-explanatory in many cases. For example:
[button setHidden:YES];
sounds better than
[button setHidden:TRUE];
First let's examine what true and false is and what gives them meaning in the first place.
we can construct a structure called if a then b else c in lambda calculus as follows:
(\ifThenElse. <use if then else>)(\a. \b. \c. a b c)
In JavaScript, This looks like this:
(function(ifThenElse) {
// use ifThenElse
})(function(a) {
return function(b) {
return function(c) {
return a(b)(c);
};
};
});
in order for ifThenElse to be useful, we need a function "true" that chooses either right or left, and does that while ignoring the other option, or a function "false" that chooses the option "true" doesn't take.
We can define these functions as follows:
(\true. <use true>)(\a. \b. a) and (\false. <use false>)(\a. \b. b)
in JavaScript it looks like this:
(function(True) {
// use True
})(function(a) {
return function(b) {
return a;
}
});
(function(False) {
// use True
})(function(a) {
return function(b) {
return b;
}
});
now we can do the following
(\true. \false. \ifThenElse. \doThis. \doThat. ifThenElse true doThis doThat)
(\a. \b. a)(\a. \b. b)(\a. \b. \c. a b c)(\a. ())(\a. ())
with doThis and doThat being (\a. ()) because lambda calculus does not offer any services such as printing/math/strings, all we can do is do nothing and say we did it(and later cheat by replacing it with services in our system that provide side effects we want)
so let's see this in action.
(function(True) {
return (function(False) {
return (function(ifThenElse) {
return (function(doThis) {
return (function(doThat) {
return ifThenElse(True)(doThis)(doThat);
});
});
});
})
})(function(a) {
return function(b) {
return a;
}
})(function(a) {
return function(b) {
return b;
}
})(function(a) {
return function(b) {
return function(c) {
return a(b)(c);
};
};
})(function(a) { console.log("you chose LEFT!"); })
(function(a) {console.log("you chose RIGHT");})();
That's a deep environment that could be simplified if we were allowed to use arrays/maps/arguments/or more than one statement to split into multiple functions, but i want to keep is as pure as I can limiting myself to functions of exactly one argument only.
notice that the name True/False has no inherent significance, we can easily rename them to yes/no, left/right, right/left, zero/one, apple/orange. It has significance in that whatever choice is made, it is only caused by the kind of chooser made it. So if "LEFT" is printed, we know that the chooser could only be true, and based on this knowledge we can guide our further decisions.
So to summarize
function ChooseRight(left) {
return function _ChooseRight_inner(right) {
return right;
}
}
function ChooseLeft(left) {
return function _ChooseLeft_inner(right) {
return left;
}
}
var env = {
'0': ChooseLeft,
'1': ChooseRight,
'false': ChooseRight,
'true': ChooseLeft,
'no': ChooseRight
'yes': ChooseLeft,
'snd': ChooseRight,
'fst': ChooseLeft
};
var _0 = env['0'];
var _1 = env['1'];
var _true = env['true'];
var _false = env['false'];
var yes = env['yes'];
var no = env['no'];
// encodes church zero or one to boolean
function lambda_encodeBoolean(self) {
return self(false)(true);
}
// decodes a Boolean to church zero or one
function lambda_decodeBoolean(self) {
console.log(self, self ? env['true'] : env['false']);
return self ? env['true'] : env['false'];
}
lambda_decodeBoolean('one' === 'two')(function() {
console.log('one is two');
})(function() {
console.log('one is not two');
})();
lambda_decodeBoolean('one' === 'one')(function() {
console.log('one is one');
})(function() {
console.log('one is not one');
})();
No, YES/NO is a different way to refer to TRUE/FALSE(1/0)
'IT story' 카테고리의 다른 글
angular2 스타일 가이드-달러 기호가있는 속성? (0) | 2020.06.11 |
---|---|
Java 해시 맵이 실제로 O (1)입니까? (0) | 2020.06.11 |
클래스 메소드에서 property () 사용 (0) | 2020.06.11 |
POM.xml에서 환경 변수를 참조하는 방법은 무엇입니까? (0) | 2020.06.11 |
jQuery show () 함수에 display : inline-block을 추가하는 방법은 무엇입니까? (0) | 2020.06.11 |