示例代码中的双括号

示例代码中的双括号

本文介绍了示例代码中的双括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在XCode生成的示例和存根中,我看到了很多这样的代码:

I see a lot of code like this in samples and in stubs that XCode generates:

if ((self = [super init])) {
}

我对条件中使用双括号的意图不清楚.

I am not clear on the intention of double parenthesis in the conditional.

推荐答案

要扩展@Anders评论,它可以保护您免受攻击的特定问题如下:

To expand on @Anders comment, the specific issue it's protecting you against goes like this:

if (foo = x) { do_something() };

90%的时间是错误.您的意思是说foo == x.但是10%的时间中,您真正的意思是将x分配给foo,然后测试真相".典范情况是while (ch = getchar()).但是if (self = [super init])是另一个很好的例子.除非您通过使用双括号告诉编译器您的意思是真的,否则编译器会认为此类情况是错误的,并会发出警告.

90% of the time this is a bug. You meant to say foo == x. But 10% of the time, you really meant "assign x to foo and then test for truth." The canonical case of this is is while (ch = getchar()). But the if (self = [super init]) is another good example. The compiler assumes that such things are mistakes and throws a warning unless you tell the compiler you really meant it by using double parentheses.

我个人就是这样:

self = [super init];
if (self != nil)
{
  ...
}
return self;

这是额外的一行,但是当init调用很长时,它使事情保持一点点清晰.

It's an extra line, but it keeps things just that tiny bit clearer when the init call is long.

顺便说一句,Big Nerd Ranch名望的Aaron Hillegass挑战了我们中的一些人,提出了任何这种self==nil支票实际上很重要的情况.这些情况确实存在,但数量极少(您可以将self添加为NSObservation观察者,并且在这种情况下不希望它成为nil).拿它值钱;在我的个人代码中,我经常跳过nil检查,但是在我的专业代码中,这是我团队标准的一部分.

As an aside, Aaron Hillegass of Big Nerd Ranch fame challenged several of us to come up with any case in which this self==nil check actually mattered. The cases exist, but they are incredibly few (you might add self as an NSObservation observer and you wouldn't want it to be nil in that case). Take it for what it's worth; in my personal code I often skip the nil check, but in my professional code it's part of my team's standard.

另一方面,由于某种原因,Apple添加了额外的gcc选项-Wmost来关闭此警告.我猜那里的人不喜欢输入多余的括号.对我来说,关闭它似乎是个坏主意.

As another aside, for some reason Apple added an extra gcc option -Wmost that turns off this warning. I guess someone there didn't like typing the extra parentheses. It seems a bad idea to me to turn it off.

这篇关于示例代码中的双括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:22