xcode 自动修复“字符串文字的直接比较具有未定义的行为”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16246462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fixing "direct comparison of a string literal has undefined behavior" automatically
提问by Someone
In Xcode, I'm getting the error "direct comparison of a string literal has undefined behavior," and I know why I'm getting it, but is there some way for me to click a button and have Xcode remove it? I'm saying this because in 370 places in my app I've gotten it.
在 Xcode 中,我收到错误“字符串文字的直接比较具有未定义的行为”,我知道我为什么会得到它,但是有什么方法可以让我单击按钮并让 Xcode 将其删除?我这么说是因为在我的应用程序的 370 个地方我已经得到了它。
回答by rickster
The clang option to disable this warning is -Wno-objc-literal-compare
.
禁用此警告的 clang 选项是-Wno-objc-literal-compare
.
However, warnings are there for a reason; this one is because comparing against NSString literals using ==
is not guaranteed to behave as you might expect. Use isEqual:
or isEqualToString:
instead and you can both get rid of this warning and avoid having this turn into a bug for you later.
然而,警告是有原因的;这是因为与使用 NSString 文字进行比较==
并不能保证其行为符合您的预期。使用isEqual:
或isEqualToString:
代替,您既可以摆脱此警告,又可以避免以后将其变成错误。
回答by Sourabh Kumbhar
You can avoid the warning using `isEqualToString` instead of `==`.
`==`?simply compares the pointers, which will usually be different even
if their contents are the same. The`isEqualToString`?method compares
their contents.