码迷,mamicode.com
首页 > Web开发 > 详细

Ojective-C:含有中文 导致NSURL初始化一直为null的解决办法

时间:2016-04-07 20:19:06      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

在学习Ojective-C过程中,需要读取文件中的内容,但发现指针变量url的值一直为nil。

代码如下:

 NSString *strUrl=@"file:///Users/fengziwu/Desktop/笔记.txt";
 NSURL *url = [[NSURL alloc] initWithString:strUrl];

技术分享

 

后来发现原因:编码问题,带中文字符的文件路径导致,需要对路径进行编码处理

NSString类中有这两个方法:

- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc NS_DEPRECATED(10_0, 10_11, 2_0, 9_0, "Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.");
- (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc NS_DEPRECATED(10_0, 10_11, 2_0, 9_0, "Use -stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding.");

前一个方法字符串进行编码,后一个方法对字符串进行解码。

解决办法如下:

 NSString *strUrl=@"file:///Users/fengziwu/Desktop/笔记.txt";
 NSURL *url = [[NSURL alloc] initWithString:[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

技术分享

 

Ojective-C:含有中文 导致NSURL初始化一直为null的解决办法

标签:

原文地址:http://www.cnblogs.com/Zev_Fung/p/5364862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!