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

匆匆过客 提交于 2019-11-26 23:14:59

问题


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 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?


回答1:


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.




回答2:


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!




回答3:


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

if ((self = [super init]))



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/4940366/ifself-super-init-llvm-warning-how-are-you-dealing-with-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!