Basic Objective-C syntax commonly used in init met

2019-09-07 05:28发布

问题:

Possible Duplicate:
Double parentheses in sample code

Often the init method in an Objective-C class will have the following line:

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

I'm just wondering if the extra parentheses are necessary. Is the following line equivalent?

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

Edit: This is indeed a duplicate of Double parentheses in sample code

回答1:

They are not necessary, but using (( and )) say "yes, I mean an assignment, not a comparison."

In fact clang will warn you about using assignment in an if condition and suggest double parentheses for unambiguity.

In general I think this could be considered bad coding style, but an exception is made here since this is a special frequently used pattern in obj-c