NSUrl fileURLWithPath returns strange chinese signs

馋奶兔 提交于 2019-12-13 03:06:50

问题


I have an NSString path to my Documents folder.

NSString* stringURL = @"/var/mobile/Applications/5667FADC-F848-40CF-A309-
7BFE598AE6AB/Library/Application Support/MyAppDirectory";

When I cast it to NSUrl with

 NSURL* url = [NSURL fileURLWithPath:stringUrl];

and NSLog(@"Created URL: %@",url);, i get some strange result:

///var/mobile/Applications/5667FADC-F848-40CF-A309-7BFE598AE6AB/Library/Application㤈㤋ތȀ乽啓汲唠䱒›楦敬⼺⼯慶⽲潭楢敬䄯灰楬慣楴湯⽳㘵㜶䅆䍄䘭㐸ⴸ〴䙃䄭〳ⴹ䈷䕆㤵䄸㙅䉁䰯扩慲祲䄯灰楬慣楴湯㈥匰灵潰瑲䴯䅹灰楄敲瑣牯⽹upport/MyAppDirectory/

Why is this so ? What am I doing wrong ?


回答1:


I didn't see any Chinese character when I log the value.

NSString* stringURL = @"/var/mobile/Applications/5667FADC-F848-40CF-A309-7BFE598AE6AB/Library/Application Support/MyAppDirectory";
NSURL* url = [NSURL fileURLWithPath:stringURL];
NSLog(@"%@",url);



回答2:


Classical mistake. Don't use NSLog (url), use NSLog (@"%@", url). The first argument to NSLog is a format string, and % characters in format strings are interpreted, not printed. For example, %s in a format string means another C-String is expected in the argument list. Since url could contain all kinds of characters, this is likely to lead to rubbish results or even crashes.




回答3:


Based on the answer you accepted from a previous question; it's because the use of stringByAddingPercentEscapesUsingEncoding will generate a printf-like formatting string containing %20S (the space between Application Support is converted to %20), which confuses NSLog():

NSURL *url = [NSURL fileURLWithString:[stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] isDirectory:YES];
NSLog(url);

use NSLog("@%", url) to avoid this error.



来源:https://stackoverflow.com/questions/23425439/nsurl-fileurlwithpath-returns-strange-chinese-signs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!