为什么我的比较 if 语句不起作用?
为什么以下代码(在可可中)不起作用?
NSString *extension = [fileName pathExtension];
NSString *wantedExtension = @"mp3";
if(extension == wantedExtension){
//work
}
在 Xcode 中,它运行时没有警告或错误,但没有执行我认为应该执行的操作。
Why is the following code (in cocoa) not working?
NSString *extension = [fileName pathExtension];
NSString *wantedExtension = @"mp3";
if(extension == wantedExtension){
//work
}
in Xcode this just runs without warnings or errors but doesn't do what I think it SHOULD do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不应该是
“==”比较指针吗? isEqual: 和 isEqualToString: 比较字符串,尽管如果您知道 extension 和 WantExtension 都是 NSString(在本例中您就是这样做的),则 isEqualToString 会更好。
实际上,如果您像我一样是一位老 C++ 和 Java 程序员,您可能会更乐意将已知不为 null 的“wantedextension”放在第一位。 在 Objective C 中,这是不必要的,因为“发送消息”(即调用方法)到 nil 会返回 0 或 false。
Shouldn't that be
"==" compares the pointers. isEqual: and isEqualToString: compare the strings, although isEqualToString is better if you know both extension and wantedExtension are NSString (which you do in this case).
Actually, if you're an old C++ and Java programmer like me, you might be happier putting the one that is known not to be null, "wantedextension", first. In Objective C that is not necessary because "sending a message" (ie calling a method) to a nil returns 0 or false.
Paul 的答案在技术上是正确的,但正如 NSString 文档中所述,“当您知道两个对象都是字符串时,此方法 [isEqualToString:] 是比 isEqual: 更快的检查相等性的方法。” 因此,对于您的示例代码,正确的测试是
如果扩展名是
nil
,则结果将为假,即使wantedExtension不是nil
,因为消息传递nil Objective-C 中的
对于BOOL
返回值函数返回 0。Paul's answer is technically correct, but as stated in the NSString documentation, "When you know both objects are strings, this method [isEqualToString:] is a faster way to check equality than isEqual:." Thus, for your example code, the correct test is
If extension is
nil
, the result will be false, even if wantedExtension is non-nil
, since messagingnil
in Objective-C returns 0 forBOOL
return-valued functions.请记住,在 Objective-C 中没有运算符重载。 在这种情况下
==
所做的是比较两个指针,这是一种完全合法且常用的用法。 您有两个指针始终指向两个不同的对象,因此==
运算符始终为 false。Remember that in Objective-C there is no operator overloading. What the
==
is doing in this case is a perfectly legal and well-used usage, comparing two pointers. You have two pointers that will always point to two different objects, so the==
operator will always be false.