带中文的路径导致NSURL初始化一直为null的问题

时间:2022-08-25 08:11:21

一、问题描述

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

代码如下:

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

带中文的路径导致NSURL初始化一直为null的问题

二、问题分析

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

三、问题解决

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]];

带中文的路径导致NSURL初始化一直为null的问题