if (self = [super init]) 与 if ((self = [super init]))

if (self = [super init]) vs. if ((self = [super init]))(if (self = [super init]) 与 if ((self = [super init])))

本文介绍了if (self = [super init]) 与 if ((self = [super init]))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚进行代码审查并开始怀疑:

Was just doing a code review and started to wonder:

我认为 if (self = [super init]) 检查将 [super init] 的返回值分配给变量 self 是否成功与否(操作价值).因此 (self = nil) 实际上是 TRUE.

I thought if (self = [super init]) checks whether assigning return value of [super init] to variable self was successful or not (value of operation). Thus (self = nil) would actually be TRUE.

我以为 if ((self = [super init])) 在赋值后检查 self 的值是什么(变量的值).因此 ((self = nil)) 将是 FALSE.

I thought if ((self = [super init])) checks what is the value of self after assignment (value of variable). Thus ((self = nil)) would be FALSE.

在初始化您自己的类时使用哪种方法是正确的?Apple 文档使用前一个(例如这里),我现在实际使用的样式.

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.

推荐答案

他们都做同样的事情.if 评估的是其中表达式的值,即赋值中的赋值.所以当 self 不是 nil 时,你继续进入 if 块.

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. So when self is not nil, you proceed into the if block.

第二种形式在它周围抛出括号,以消除任何潜在的编译器关于条件内赋值的警告,这通常是不好的做法,可能是一个错字.但这是惯用的 Objective-C,所以用第一种方式就可以了.

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.

这篇关于if (self = [super init]) 与 if ((self = [super init]))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:if (self = [super init]) 与 if ((self = [super init]))

基础教程推荐