Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
309 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...