Why is my comparing if statement not working?

2019-01-12 10:09发布

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.

3条回答
戒情不戒烟
2楼-- · 2019-01-12 11:04

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.

查看更多
太酷不给撩
3楼-- · 2019-01-12 11:13

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.

查看更多
forever°为你锁心
4楼-- · 2019-01-12 11:15

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]) {
   ...
}
查看更多
登录 后发表回答