问题
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