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

查看:120
本文介绍了if(self = [super init])vs. 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])vs. if((self = [super init]))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆