Why my comparison if the operator does not work?

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

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

in Xcode, it just works without warning or error, but does not do what I think SHOULD do.

+3
source share
3 answers

Must not be

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

"==" compares pointers. isEqual: and isEqualToString: compare strings, although isEqualToString is better if you know both the extension and wantedExtension are NSString (what you do in this case).

, ++ Java, , , , , , , " ". Objective C , " " (.. ) nil 0 false.

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

Paul , , NSString, " , , [isEqualToString:] - , isEqual:." ,

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

nil, , wantedExtension nil, nil Objective-C 0 BOOL .

+9

, Objective-C . , == , , . , , == false.

+2

Source: https://habr.com/ru/post/1702320/


All Articles