Tutorial :Double parentheses in sample code



Question:

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.


Solution:1

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.


Solution:2

its just to avoid getting a warning.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »