stringByAddingPercentEscapesUsingEncoding:和stringByReplacingPercentEscapesUsingEncoding有什么区别:

时间:2014-02-17 12:44:26

标签: ios objective-c nsstring url-encoding

两种方法stringByAddingPercentEscapesUsingEncoding:stringByReplacingPercentEscapesUsingEncoding:之间的区别是什么?

我已多次阅读NSString Class Reference但仍然没有阅读。

另外,有没有办法强制这些方法编码“+”符号?

my iPhone app我必须urlencode base64编码(即字母,数字,加号和斜杠)头像,最后使用CFURLCreateStringByAddingPercentEscapes方法代替上述方法......

- (NSString*)urlencode:(NSString*)str
{
    return (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
        NULL,
        (__bridge CFStringRef) str,
        NULL,
        CFSTR("+/"),
        kCFStringEncodingUTF8));
}

1 个答案:

答案 0 :(得分:17)

stringByAddingPercentEscapesUsingEncoding会将Unicode *字符转换为转义百分比格式。

stringByReplacingPercentEscapesUsingEncoding将执行相反的操作,将百分比转义转换为Unicode *。

*实际上不是Unicode,而是您选择的编码。

示例:

NSString *rawText = @"One Broadway, Cambridge, MA"; 
NSString *encodedText = [rawText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Encoded text: %@", encodedText);
NSString *decodedText = [encodedText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Original text: %@", decodedText);

这是输出:

Encoded text: One%20Broadway,%20Cambridge,%20MA

Original text: One Broadway, Cambridge, MA

缺点:stringByAddingPercentEscapesUsingEncoding不编码保护字符,如&符号(&)和斜杠(/)

解决方法:改为使用基础功能CFURLCreateStringByAddingPercentEscapes

来源:http://cybersam.com/ios-dev/proper-url-percent-encoding-in-ios