2012-01-30 53 views
2

我想转换NSURLNSString在我的程序中的其他地方使用。NSURL到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); 
    } 

}]; 
} 

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

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 

有人能指出我在做什么错误?

回答

6

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

要获取url的实际路径,请发送url -path消息。因此,要获得一个字符串的路径:

NSString* filePath = [theDoc path]; 
NSLog(@"the url: %@", theDoc); 
NSLog(@"the path: %@", filePath); 

这应该打印以下(根据你上面的日志):

the url: file://localhost/Users/*****/Desktop/mockupsite.jpg 
the file: /Users/*****/Desktop/mockupsite.jpg 
+0

非常感谢你澄清。我希望除了“我觉得自己像一个愚蠢的笨蛋”之外还有别的话要说。 – GreenWire 2012-01-30 01:07:43