我如何摆脱“未使用的变量"?在Xcode中警告? [英] How can I get rid of an "unused variable" warning in Xcode?

查看:171
本文介绍了我如何摆脱“未使用的变量"?在Xcode中警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全理解为什么会发生未使用的变量警告.我一般不想抑制它们,因为它们在大多数情况下都非常有用.但是,请考虑以下(伪造的)代码.

I understand exactly why unused variable warnings occur. I don't want to suppress them in general, because they are incredibly useful in most cases. However, consider the following (contrived) code.

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

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

Xcode reports that saved is an unused variable, when of course it isn't. I suspect this is because NSAssert1 is a macro. The NS_BLOCK_ASSERTIONS macro is not defined, so Objective C assertions are definitely enabled.

虽然它没有任何伤害,但我发现它不整洁且令人讨厌,并且我想压制它,但是我不确定该怎么做.将变量分配给自身可以摆脱编译器警告,但是如果存在这种情况,我宁愿以正确"的方式进行操作.

While it doesn't hurt anything, I find it untidy and annoying, and I want to suppress it, but I'm not sure how to do so. Assigning the variable to itself gets rid of the compiler warning, but I'd rather do it the "right" way if such a thing exists.

推荐答案

我不确定新的LLVM编译器是否仍然支持它,但是GCC具有未使用"属性,您可以使用它来抑制该警告:

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];

或者(如果LLVM不支持以上内容),您可以将变量声明分成单独的一行,以确保无论宏是否扩展,该变量都将被使用":

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];

这篇关于我如何摆脱“未使用的变量"?在Xcode中警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆