Why is my comparing if statement not working?

大城市里の小女人 提交于 2019-11-26 22:26:35

问题


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.


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/484709/why-is-my-comparing-if-statement-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!