简体   繁体   中英

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

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?

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!

只需使用两对括号就可以清楚地告诉编译器您是故意分配的:

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. 在此输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM