为什么我的比较 if 语句不起作用?

发布于 2024-07-13 05:46:23 字数 227 浏览 6 评论 0原文

为什么以下代码(在可可中)不起作用?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雪花飘飘的天空 2024-07-20 05:46:23

不应该是

if ([extension isEqualToString:wantedExtension]) {
...
}

“==”比较指针吗? isEqual: 和 isEqualToString: 比较字符串,尽管如果您知道 extension 和 WantExtension 都是 NSString(在本例中您就是这样做的),则 isEqualToString 会更好。

实际上,如果您像我一样是一位老 C++ 和 Java 程序员,您可能会更乐意将已知不为 null 的“wantedextension”放在第一位。 在 Objective C 中,这是不必要的,因为“发送消息”(即调用方法)到 nil 会返回 0 或 false。

if ([wantedExtension isEqualToString:extension]) {
   ...
}

Shouldn't that be

if ([extension isEqualToString:wantedExtension]) {
...
}

"==" 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.

if ([wantedExtension isEqualToString:extension]) {
   ...
}
紫瑟鸿黎 2024-07-20 05:46:23

Paul 的答案在技术上是正确的,但正如 NSString 文档中所述,“当您知道两个对象都是字符串时,此方法 [isEqualToString:] 是比 isEqual: 更快的检查相等性的方法。” 因此,对于您的示例代码,正确的测试是

if([extension isEqualToString:wantedExtension]) {
    ...
}

如果扩展名是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 isEqualToString:wantedExtension]) {
    ...
}

If extension is nil, the result will be false, even if wantedExtension is non-nil, since messaging nil in Objective-C returns 0 for BOOL return-valued functions.

温柔戏命师 2024-07-20 05:46:23

请记住,在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文