【问题标题】:Objective-C 'CFURLCreateStringByAddingPercentEscapes' is deprecated: first deprecated in iOS 9.0不推荐使用 Objective-C 'CFURLCreateStringByAddingPercentEscapes':首先在 iOS 9.0 中不推荐使用
【发布时间】:2015-10-02 13:05:09
【问题描述】:

我收到了这个警告:

'CFURLCreateStringByAddingPercentEscapes' is deprecated: first deprecated in iOS 9.0 - Use [NSString 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).

在这一行:

return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)self, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding));

我试图用谷歌搜索解决方案,但我什么都不懂。请帮忙。

我尝试了以下方法:

return [NSString stringByAddingPercentEncodingWithAllowedCharacters:(NULL, (CFStringRef)self, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding))];

并收到了这个新警告:

Class method '+stringByAddingPercentEncodingWithAllowedCharacters:' not found (return type defaults to 'id')

Expression result unused

【问题讨论】:

  • 改用[NSString stringByAddingPercentEncodingWithAllowedCharacters:]
  • 对不起,我不想听起来很粗鲁,但是你写过一行 Objective-C 吗?
  • 我确实觉得这很粗鲁。我有,但我不擅长代码转换
  • 请查看stringByAddingPercentEncodingWithAllowedCharacters: 的文档。它不是类方法,它有一个参数,即NSCharacterSet

标签: ios objective-c


【解决方案1】:

好的,我去试试:

- (NSString *)escaped
{
#if (TARGET_OS_MAC && (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_9))
    NSString * encodedString = (NSString *)
    CFURLCreateStringByReplacingPercentEscapes(
                                               NULL,
                                               (CFStringRef)self,
                                               NULL);
#else
    NSString * encodedString = (NSString *)
    CFURLCreateStringByAddingPercentEscapes(
        NULL,
        (CFStringRef)self,
        NULL,
        (CFStringRef)@"!*'();:@&=+$,/?%#[]",
        kCFStringEncodingUTF8 );
#endif
    return encodedString;
}

【讨论】: