Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

objective c - Double parentheses in sample code

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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.

Personally, I just do it this way:

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

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...