问题描述
我看了,现在我偏执到 BOOL
键入 ID
的隐式铸造变量。
假设我有一个较低位的危险的指针归零,因此,它强制转换为 BOOL
将产生 NO
,即使它指向一个有效的对象。我们称之为危险的指针富
。
如何做简单的if语句工作?
请问if语句投富
到 BOOL
时,计算该条件?还是将它转换为一个纯粹的布尔?
如果(富)
{
[myArray的ADDOBJECT:美孚]。
}
它的工作原理相同的方式在三元前pressions?
//这是否休息的时候foo是危险?
self.titleLabel.hidden = foo的?是:否;
还是会如果我这样做三元只有突破:
//我pretty肯定现在打破
self.titleLabel.hidden =((BOOL)富)?是:否;
我觉得我失去了用C基本的东西有关逻辑运算,以及它们如何与 BOOL
。请帮赐教。
Never, since this phrase is semantically incorrect. A cast is, by definition, explicit. What you're asking about is called an "implicit type conversion" (coercion - thanks, Josh!).
Also, strictly speaking, the conditionals in Objective-C are not special: they're inherited from C. So expressions, when needed to evaluated as booleans, aren't treated as BOOL
, but as int
.
// Does this break when foo is 'dangerous'?`
self.titleLabel.hidden = foo ? YES : NO;
No, it doesn't. (expr)
when used as a "boolean" expression, is equivalent to (expr != 0)
. No risks here.
// I'm pretty sure it breaks now
self.titleLabel.hidden = ((BOOL)foo) ? YES : NO;
Now this can break, since BOOL
is just typedeffed to signed char
, which is 8 bit on iOS. Thus, if foo
, which is a (32-bit) pointer, gets truncated to 8 bits, and the lower 8 bits of the pointer were all zero, but the pointer itself wasn't nil
, this will incorrectly report false. You don't want to do this superfluous, ugly and dangerous cast. If you want to be more explicit, write
var = (obj != nil) ? valueOne : valueTwo;
instead.
这篇关于什么时候Objective-C的隐式转换为BOOL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!