NSURL到NSString转换做了一些奇怪的事情

Gre*_*ire 2 macos xcode objective-c interface-builder

我正在尝试将a转换NSURL为a NSString以在我的程序中的其他位置使用.

这是我的代码:

- (IBAction)openExistingDocument:(id)sender {
NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setCanChooseDirectories:NO];
[panel setAllowsMultipleSelection:NO];
[panel setMessage:@"Please select a File or Folder containing your character's .png layers"];

[panel beginWithCompletionHandler:^(NSInteger result){
    if (result == NSFileHandlingPanelOKButton) {

        NSURL*  theDoc = [[panel URLs] objectAtIndex:0];
        NSString* unformattedURL = [NSString stringWithContentsOfURL:theDoc encoding:NSASCIIStringEncoding error:NULL];
        NSString * formattedURL = [unformattedURL stringByReplacingOccurrencesOfString:@"file:/" withString:@""];
        NSLog(@"the url says:%@", theDoc);
        NSLog(@"the unformatted string says: %@", unformattedURL);
        NSLog(@"the formatted string says: %@", formattedURL);
    }

}];
}
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,这是我的命令行输出:

2012-01-29 18:43:19.205 Cocos2dCharacterRigger[516:407] the url says:file://localhost/Users/*****/Desktop/mockupsite.jpg
2012-01-29 18:43:19.213 Cocos2dCharacterRigger[516:407] the unformatted string says: ÿØÿá.]Exif
2012-01-29 18:43:19.219 Cocos2dCharacterRigger[516:407] the formatted string says: ÿØÿá.]Exif
Run Code Online (Sandbox Code Playgroud)

有人能指出我做错了什么吗?

Jas*_*oco 6

您正在将URL中文件的内容加载到字符串中.您正在将文件作为ASCII字符串加载(该文件几乎肯定不是 - 它是图像)并且您忽略任何错误.

要获取URL的实际路径,请发送-path消息的URL .因此,要获取路径的字符串:

NSString* filePath = [theDoc path];
NSLog(@"the url: %@", theDoc);
NSLog(@"the path: %@", filePath);
Run Code Online (Sandbox Code Playgroud)

这应该打印以下内容(基于您上面的日志):

the url: file://localhost/Users/*****/Desktop/mockupsite.jpg
the file: /Users/*****/Desktop/mockupsite.jpg
Run Code Online (Sandbox Code Playgroud)