[英]if (self = [super init]) vs. if ((self = [super init]))
Was just doing a code review and started to wonder: 只是在进行代码审查,并开始怀疑:
I thought if (self = [super init])
checks whether assigning return value of [super init]
to variable self
was successful or not ( value of operation ). 我以为
if (self = [super init])
检查是否将[super init]
返回值分配给变量self
( 操作的值 )是否成功。 Thus (self = nil)
would actually be TRUE
. 因此
(self = nil)
实际上是TRUE
。
I thought if ((self = [super init]))
checks what is the value of self
after assignment ( value of variable ). 我想
if ((self = [super init]))
检查赋值后self
的值是什么( variable的值 )。 Thus ((self = nil))
would be FALSE
. 因此
((self = nil))
将为FALSE
。
Which one is the correct way to use when initialising your own classes? 初始化自己的类时,哪种方法是正确的? Apple documentation uses the former one ( for example here ), which style I'm actually using now.
Apple文档使用的是前一种( 例如,在此处 ),而我现在正在实际使用这种样式。
They both do the same thing. 他们俩都做同样的事情。 The thing that the
if
evaluates is the value of the expression inside it, which is the assigned value in an assignment. if
评估的是它内部表达式的值,它是赋值中的赋值。 So when self
is not nil, you proceed into the if
block. 因此,当
self
不为零时,您进入if
块。
The second form throws parens around it to silence any potential compiler warnings about assignments inside conditionals, which is generally bad practice and possibly a typo. 第二种形式在其周围抛出括号,以使关于条件内部赋值的任何潜在编译器警告均保持沉默,这通常是一种不好的做法,而且可能是拼写错误。 But this is idiomatic Objective-C, so it's fine to do it the first way.
但这是惯用的Objective-C,因此最好采用第一种方法。
As others have said the parentheses don't matter in this case. 正如其他人所说,在这种情况下,括号并不重要。 Where they do matter is if you explicitly check against nil:
它们的作用在于您是否明确检查nil:
if (self = [super init] != nil) // wrong!
if ((self = [super init]) != nil) // right
!= has higher precedence than = so in the first case you assign the boolean result of [super init] != nil
(probably true) to self and then does the test for the if. !=的优先级比=高,因此在第一种情况下,您将
[super init] != nil
(可能为true)的布尔结果分配给self,然后对if进行测试。
Personally, I don't care for either but prefer to do the assignment explicitly outside of the test. 就我个人而言,我也不在乎,但更喜欢在测试之外明确地进行作业。 This is a reflection of my programming background that has led me to the belief that booleans are a different type from integers and pointers and that assignments are not expressions, even though, in the case of the C implementation, I am wrong.
这反映了我的编程背景,使我相信布尔值与整数和指针是不同的类型,并且赋值不是表达式,即使在C实现的情况下,我错了。
self = [super init];
if (self != nil)
"An assignment expression has the value of the left operand after the assignment" (C99), so either way it has the value of variable , as you put it. “赋值表达式具有赋值后的左操作数的值”(C99),因此无论哪种方式,赋值表达式都具有variable的值 。 The extra parentheses make no difference (except possibly for warnings).
多余的括号没有区别(警告可能除外)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.