Why is my comparing if statement not working?

前端 未结 3 376
心在旅途
心在旅途 2020-12-04 02:44

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

NSString *extension = [fileName pathExtension];
NSString *wantedExtension = @\"mp3\";
if(extension == wante         


        
3条回答
  •  囚心锁ツ
    2020-12-04 03:08

    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.

提交回复
热议问题