为什么我的比较 if 语句不起作用? [英] Why is my comparing if statement not working?

查看:32
本文介绍了为什么我的比较 if 语句不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why is the following code (in cocoa) not working?

NSString *extension = [fileName pathExtension];
NSString *wantedExtension = @"mp3";
if(extension == wantedExtension){
//work
}

在 Xcode 中,这只是在没有警告或错误的情况下运行,但没有做我认为应该做的事情.

in Xcode this just runs without warnings or errors but doesn't do what I think it SHOULD do.

推荐答案

不应该是

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

"==" 比较指针.isEqual: 和 isEqualToString: 比较字符串,不过如果你知道 extension 和 WantedExtension 都是 NSString(你在本例中这样做),isEqualToString 会更好.

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

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

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]) {
   ...
}

这篇关于为什么我的比较 if 语句不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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