iOS9.0之後NSStringencode方法替換

ro_bber發表於2017-07-18

在iOS 9.0之後,以前常用的NSString編碼的方法stringByAddingPercentEscapesUsingEncoding:被棄用了,專案中可能會出現一堆如下️:

`stringByAddingPercentEscapesUsingEncoding:` is deprecated: first deprecated in iOS 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 *)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.");

很明白,用stringByAddingPercentEncodingWithAllowedCharacters:方法替換之。

這個方法官方文件是這麼說的:

// Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.

最後一句Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.,意思就是說,任何非7-bit ASCII字元擱到allowedCharacters裡面也將被忽略,也就是allowedCharacters裡面的字元跟7-bit ASCII字元不會被編碼。

換句話說,上面方法在處理的時候會編碼url的中的非7-bit ASCII字元,如這些【`#%^{}”[]|<>】,如果需要忽略之,需要通過(NSCharacterSet *)allowedCharacters這個引數指定。總結如下

[aString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//等價於
[aString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}"[]|\<> "]];

注意:

  1. 字符集最後是一個空格!
  2. 這裡字符集的意思就是,字串中含有字符集裡面的字元將不會被編碼。

另外,URL中常用的NSCharacterSet型別定義在分類NSCharacterSet (NSURLUtilities)中,包含字符集如下:

URLHostAllowedCharacterSet      "#%/<>?@^`{|}

URLFragmentAllowedCharacterSet  "#%<>[]^`{|}

URLPasswordAllowedCharacterSet  "#%/:<>?@[]^`{|}

URLPathAllowedCharacterSet      "#%;<>?[]^`{|}

URLQueryAllowedCharacterSet     "#%<>[]^`{|}

URLUserAllowedCharacterSet      "#%/:<>?@[]^`

以上,還在等什麼,全域性搜尋替換吧,消滅️!

喜歡我的可以關注收藏我的個人部落格:RobberJJ


相關文章