开发者

if(self = [super init]) - LLVM warning! How are you dealing with it?

开发者 https://www.devze.com 2023-02-09 03:56 出处:网络
Prior to Xcode 4 with LLVM this passed the compiler unnoticed. Assignment within the conditional is perfectly intentional and a Cocoa idiom.

Prior to Xcode 4 with LLVM this passed the compiler unnoticed. Assignment within the conditional is perfectly intentional and a Cocoa idiom.

Xcode 4 with LLVM compiler selected never fails to complain, and not just at compile time, as soon as you type it the yellow warning icon appears. Turning off warnings as errors and just ignoring the warning doesn't seem like a good idea. Moving the assignment out of the 开发者_StackOverflow社区parentheses wastes space. Having to turn off this warning with a pragma for every new project will become tedious.

How are you dealing with it? What's the new idiom going to be?


This is actually a very old warning, it was just off by default with GCC and with Clang 1.6. Xcode should actually give you a suggestion for how to fix it - namely, double the parentheses.

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

The extra pair of parens tells the compiler that you really did intend to make an assignment in the conditional.


If you create an init method from the newer Xcode text macros, you'll noticed that the new blessed way to do init is:

- (id)init {
    self = [super init];
    if (self) {
        <#initializations#>
    }
    return self;
}

This avoids the warning. Though personally in my own code if I come across this I've simply been applying the method Kevin showed.

Something good to know!


Just use two pairs of parentheses to make it clear to the compiler that you're assigning on purpose:

if ((self = [super init]))


Bring up the project navigator and choose your project. In the main window that appears, choose "All". Under the section "LLVM compiler 2.0 - Warnings", choose "Other Warning Flags". Add the flag "Wno-idiomatic-parentheses" for both "Debug" and "Release." Now clean and recompile.

if(self = [super init]) - LLVM warning! How are you dealing with it?


As a few others have suggested you should add an extra set of parenthesis.

I'm far from a regular expression guru so feel free to clean this up but this find and replace in Xcode fixed about 95% of my instances:

Replace: if\s*\({1}\s*self\s*={1}(.*)\){1}
With:    if ((self =\1))

Be careful because this will also find if (self == ...), so use preview and uncheck those or fix my regex :)

And start using self = ...; if (self), it's cleaner.

0

精彩评论

暂无评论...
验证码 换一张
取 消