在 Xcode,我怎样才能摆脱“未使用变量”的警告?

我完全理解为什么会出现未使用的变量警告。我不想压制它们,因为它们在大多数情况下都非常有用。但是,请考虑以下(人为的)代码。

NSError *error = nil;
BOOL saved = [moc save:&error];
NSAssert1(saved, @"Dude!!1! %@!!!", error);

Xcode 报告 saved是一个未使用的变量,当然它不是。我怀疑这是因为 NSAssert1是一个宏。NS_BLOCK_ASSERTIONS宏是定义为 没有的,因此肯定启用了 Objective C 断言。

虽然它不会伤害任何东西,但是我发现它不整洁而且令人讨厌,我想抑制它,但是我不知道如何去做。将变量赋值给它自己可以消除编译器的警告,但是如果存在这种情况,我宁愿采用“正确”的方式。

63531 次浏览

I'm unsure if it's still supported in the new LLVM compiler, but GCC has an "unused" attribute you can use to suppress that warning:

BOOL saved __attribute__((unused)) = [moc save:&error];

Alternatively (in case LLVM doesn't support the above), you could split the variable declaration into a separate line, guaranteeing that the variable would be "used" whether the macro expands or not:

BOOL saved = NO;
saved = [moc save:&error];

In Xcode you can set the warnings for "Unused Variables." Go to "Build Settings" for the target and filter with the word "unused"

Here is a screenshot: Builld Settings Screenshot

I suggest you only change it for Debug. That way you don't miss anything in your release version.

Using Xcode 4.3.2 and found out that this seems to work (less writing)

BOOL saved __unused;
NSError *error = nil;
BOOL saved = [moc save:&error];
NSAssert1(saved, @"Dude!!1! %@!!!", error);
#pragma unused(saved)

Try like this. It is working for me. It will work for you, too.

The only simple and portable way to mark variable as used is… to use it.

BOOL saved = ...;
(void)saved; // now used

You may be happy with already described compiler-specific extensions, though.

try with: __unused attribute. Works in Xcode 5

You can set "No" LLVM compliler 2.0 warning on "Release" enter image description here

Make it take up two lines. Separate the declaration and default value

BOOL enabled = NO;


// ...


BOOL enabled;


enabled = NO;

This is the way you do it in C and therefore also Objective-C.

Even though you do not have warnings enabled, it's always a good idea to mark the return value as explicitly ignored. It also goes to show other developers, that you have not just forgotten about the return value – you have indeed explicitly chosen to ignore it.

(void)[moc save:&error];

EDIT: Compilers ignore casts to void, so it should not affect performance – it's just a nice clean human annotation.

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
NSUInteger abc; /// Your unused variable
#pragma clang diagnostic pop

SOURCE